name: Build & Publish to DockerHub (from VERSION + Release)

on:
  pull_request:
    branches: [ main ]
  push:
    branches: [ main ]

permissions:
  contents: write    # create tag + release
  pull-requests: read

jobs:
  docker:
    runs-on: ubuntu-latest

    env:
      PLATFORMS: ${{ github.event_name == 'pull_request' && 'linux/amd64' || 'linux/amd64,linux/arm64' }}

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Read VERSION
        id: ver
        run: |
          if [[ ! -f VERSION ]]; then echo "VERSION missing"; exit 1; fi
          RAW=$(tr -d ' \n' < VERSION)
          if [[ -z "$RAW" ]]; then echo "VERSION empty"; exit 1; fi
          if [[ "$RAW" =~ ^v ]]; then TAG="$RAW"; NUM="${RAW#v}"; else TAG="v${RAW}"; NUM="$RAW"; fi
          
          # Get repository name for DockerHub
          REPO_NAME=$(echo "${GITHUB_REPOSITORY}" | cut -d'/' -f2)
          
          echo "TAG=$TAG" >> $GITHUB_ENV
          echo "NUM=$NUM" >> $GITHUB_ENV
          echo "DOCKER_REPO=${{ secrets.DOCKER_HUB_USERNAME }}/${REPO_NAME}" >> $GITHUB_ENV
          echo "DOCKER_TAGS=${{ secrets.DOCKER_HUB_USERNAME }}/${REPO_NAME}:${NUM},${{ secrets.DOCKER_HUB_USERNAME }}/${REPO_NAME}:latest" >> $GITHUB_ENV
          echo "Resolved TAG=$TAG NUM=$NUM"

      - name: Create tag (if missing)
        if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }}
        uses: actions/github-script@v7
        with:
          script: |
            const tag = process.env.TAG;
            const sha = context.sha;
            const { owner, repo } = context.repo;
            try {
              await github.rest.git.getRef({ owner, repo, ref: `tags/${tag}` });
              core.info(`Tag ${tag} exists`);
            } catch (e) {
              if (e.status === 404) {
                core.info(`Creating tag ${tag} -> ${sha}`);
                await github.rest.git.createRef({ owner, repo, ref: `refs/tags/${tag}`, sha });
              } else { throw e; }
            }

      - name: Update draft release notes
        if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }}
        id: drafter
        uses: release-drafter/release-drafter@v6
        with:
          config-name: release-drafter.yml
          publish: false
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Publish GitHub Release
        if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }}
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ env.TAG }}
          name: NFOGuard ${{ env.TAG }}
          draft: false
          prerelease: false
          body: ${{ steps.drafter.outputs.body }}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Set up QEMU
        if: ${{ env.PLATFORMS == 'linux/amd64,linux/arm64' }}
        uses: docker/setup-qemu-action@v3

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

      - name: Log in to DockerHub
        if: ${{ github.event_name != 'pull_request' }}
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKER_HUB_USERNAME }}
          password: ${{ secrets.DOCKER_HUB_TOKEN }}

      - name: Build & Push (main)
        uses: docker/build-push-action@v5
        with:
          context: .
          file: ./Dockerfile
          push: ${{ github.event_name != 'pull_request' }}
          platforms: ${{ env.PLATFORMS }}
          tags: ${{ env.DOCKER_TAGS }}
          build-args: |
            APP_VERSION=${{ env.NUM }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
          provenance: false
