name: Promote to Production

on:
  workflow_dispatch:
    inputs:
      tag:
        description: "Image tag to promote (e.g. 2026.03.28-f1b85bf)"
        required: true
        type: string

jobs:
  promote:
    name: Promote to Production
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: read
    steps:
      - name: Validate tag format
        run: |
          TAG="${{ inputs.tag }}"
          if ! echo "$TAG" | grep -qE '^[0-9]{4}\.[0-9]{2}\.[0-9]{2}-[a-f0-9]{7}$'; then
            echo "::error::Invalid tag format: '$TAG'. Expected format: YYYY.MM.DD-sha7 (e.g. 2026.03.28-f1b85bf)"
            exit 1
          fi
          echo "Tag format valid: $TAG"

      - name: Verify image exists in GHCR
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          TAG="${{ inputs.tag }}"
          # Check that the API image exists — if API was pushed, web/migrate were too
          if ! gh api "/orgs/groombook/packages/container/api/versions" --jq ".[].metadata.container.tags[]" 2>/dev/null | grep -qF "$TAG"; then
            echo "::error::Image ghcr.io/groombook/api:$TAG not found in GHCR. Verify the tag was built and pushed."
            exit 1
          fi
          echo "Image verified: ghcr.io/groombook/api:$TAG exists"

      - name: Generate infra repo token
        id: infra-token
        uses: tibdex/github-app-token@v2
        with:
          app_id: ${{ vars.GH_APP_ID }}
          private_key: ${{ secrets.GH_APP_PRIVATE_KEY }}

      - name: Clone groombook/infra
        run: |
          git clone https://x-access-token:${{ steps.infra-token.outputs.token }}@github.com/groombook/infra.git /tmp/infra

      - name: Install yq
        run: |
          sudo wget -qO /usr/local/bin/yq https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64
          sudo chmod +x /usr/local/bin/yq

      - name: Update prod overlay image tags and base Job names
        env:
          TAG: ${{ inputs.tag }}
        run: |
          cd /tmp/infra
          PROD_KUST="apps/groombook/overlays/prod/kustomization.yaml"

          SHORT_SHA="${TAG##*-}"
          export SHORT_SHA
          export TAG

          yq -i '(.images[] | select(.name == "ghcr.io/groombook/api")).newTag = env(TAG)' "$PROD_KUST"
          yq -i '(.images[] | select(.name == "ghcr.io/groombook/web")).newTag = env(TAG)' "$PROD_KUST"
          yq -i '(.images[] | select(.name == "ghcr.io/groombook/migrate")).newTag = env(TAG)' "$PROD_KUST"
          yq -i '(.images[] | select(.name == "ghcr.io/groombook/seed")).newTag = env(TAG)' "$PROD_KUST"

          # Update migrate Job name to include short SHA (immutable template fix)
          MIGRATE_JOB="apps/groombook/base/migrate-job.yaml"
          if [ -f "$MIGRATE_JOB" ]; then
            yq -i '.metadata.name = "migrate-schema-" + env(SHORT_SHA)' "$MIGRATE_JOB"
            yq -i '.metadata.annotations."groombook.app/deploy-version" = env(TAG)' "$MIGRATE_JOB"
          fi

          # Update seed Job name to include short SHA (immutable template fix)
          SEED_JOB="apps/groombook/base/seed-job.yaml"
          if [ -f "$SEED_JOB" ]; then
            yq -i '.metadata.name = "seed-test-data-" + env(SHORT_SHA)' "$SEED_JOB"
            yq -i '.metadata.annotations."groombook.app/deploy-version" = env(TAG)' "$SEED_JOB"
          fi

          git -C /tmp/infra diff --stat

      - name: Create PR on groombook/infra
        env:
          TAG: ${{ inputs.tag }}
          GH_TOKEN: ${{ steps.infra-token.outputs.token }}
        run: |
          cd /tmp/infra
          git config user.name "groombook-engineer[bot]"
          git config user.email "3141748+groombook-engineer[bot]@users.noreply.github.com"
          git checkout -b "release/promote-prod-${TAG}"
          git add apps/groombook/overlays/prod/ apps/groombook/base/migrate-job.yaml apps/groombook/base/seed-job.yaml
          git commit -m "release: promote ${TAG} to production"
          git push -u origin "release/promote-prod-${TAG}"
          gh pr create \
            --repo groombook/infra \
            --base main \
            --head "release/promote-prod-${TAG}" \
            --title "release: promote ${TAG} to production" \
            --body "Promote image tag ${TAG} to production after UAT sign-off. cc @cpfarhood"

      - name: Notify on failure
        if: failure()
        uses: actions/github-script@v7
        with:
          script: |
            github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
              body: '## Production Promotion Failed\n\nThe `promote-prod` workflow failed. Check the workflow run logs for details.'
            });
