name: Release Pipeline

on:
  release:
    types: [ created ]
  push:
    branches: [ main ]
  workflow_dispatch:
    inputs:
      tag:
        description: 'Custom tag name for the image'
        required: true
        type: string
      ref:
        description: 'Git ref to checkout'
        required: true
        default: 'main'
        type: string

env:
  IMAGE_NAME: wygiwyh

concurrency:
  group: release
  cancel-in-progress: false

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write # Needed if you switch to GHCR, good practice

    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          ref: ${{ inputs.ref || github.ref }}

      - name: Log in to Docker Hub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      # This action handles all the logic for tags (nightly vs release vs custom)
      - name: Docker Metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ secrets.DOCKERHUB_USERNAME }}/${{ env.IMAGE_NAME }}
          tags: |
            # Logic for Push to Main -> nightly
            type=raw,value=nightly,enable=${{ github.event_name == 'push' }}
            # Logic for Release -> semver and latest
            type=semver,pattern={{version}},enable=${{ github.event_name == 'release' }}
            type=raw,value=latest,enable=${{ github.event_name == 'release' }}
            # Logic for Manual Dispatch -> custom input
            type=raw,value=${{ inputs.tag }},enable=${{ github.event_name == 'workflow_dispatch' }}

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3

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

      - name: Build and push
        uses: docker/build-push-action@v6
        with:
          context: .
          file: ./docker/prod/django/Dockerfile
          push: true
          provenance: false
          # Pass the calculated tags from the meta step
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          build-args: |
            VERSION=${{ steps.meta.outputs.version }}
          platforms: linux/amd64,linux/arm64

          # --- CACHE CONFIGURATION ---
          # We set a specific 'scope' key.
          # This allows the Release tag to see the cache created by the Main branch.
          cache-from: type=gha,scope=build-cache
          cache-to: type=gha,mode=max,scope=build-cache
