name: Build and Push Docker Image

on:
  push:
    tags:
      - 'v*'
  workflow_dispatch:
    inputs:
      tag:
        description: 'Docker image tag (e.g., v1.0.0, latest)'
        required: false
        default: 'latest'
      push_to_registry:
        description: 'Push to registry?'
        required: false
        default: 'true'

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    container:
      image: catthehacker/ubuntu:act-latest
    
    steps:
      - name: Checkout code
        uses: actions/checkout@v3

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v2

      - name: Login to Docker Registry
        uses: docker/login-action@v2
        with:
          registry: ${{ secrets.DOCKER_REGISTRY_URL }}
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}

      - name: Extract metadata
        id: meta
        uses: docker/metadata-action@v4
        with:
          images: ${{ secrets.DOCKER_REGISTRY_URL }}/crew_admin
          tags: |
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=semver,pattern={{major}}
            type=raw,value=latest

      - name: Build and push
        uses: docker/build-push-action@v4
        with:
          context: .
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=registry,ref=${{ secrets.DOCKER_REGISTRY_URL }}/crew_admin:buildcache
          cache-to: type=registry,ref=${{ secrets.DOCKER_REGISTRY_URL }}/crew_admin:buildcache,mode=max
