name: Main CI-Frontend

on:
  workflow_dispatch:
  push:
    branches:
      - main
    paths:
      - 'client/**/*.html'
      - 'client/**/*.png'
      - 'client/**/*.json'
      - 'client/**/*.txt'
      - 'client/**/*.ts'
      - 'client/**/*.tsx'
      - 'client/**/*.js'
      - 'client/Dockerfile'
      - 'client/Caddyfile'
      - '.github/workflows/main-client.yml'

jobs:
  build-and-push:
    name: Build & Push
    runs-on: ubuntu-latest
    permissions:
      contents: write
      packages: write

    steps:
      - name: Checkout code
        uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Set lowercase repo name
        id: repo
        run: echo "name=${GITHUB_REPOSITORY,,}" >> $GITHUB_OUTPUT

      - name: Generate version tag
        id: version
        run: |
          DATE=$(date +'%Y.%m.%d')
          TAG="app-v${DATE}.${{ github.run_number }}"
          echo "tag=${TAG}" >> $GITHUB_OUTPUT
          echo "Generated tag: ${TAG}"

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

      - name: Log in to GitHub Container Registry
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Find PR number
        id: find_pr
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          PR_NUMBER=$(gh pr list --search "${{ github.sha }}" --state merged --json number --jq '.[0].number')
          if [ -z "$PR_NUMBER" ]; then
            echo "No merged PR found for this commit. Falling back to 'candidate' tag."
            PR_NUMBER="candidate"
          else
            PR_NUMBER="pr-${PR_NUMBER}"
          fi
          echo "tag=${PR_NUMBER}" >> $GITHUB_OUTPUT

      - name: Promote Docker image
        run: |
          docker buildx imagetools create \
            --tag ghcr.io/${{ steps.repo.outputs.name }}/app:latest \
            --tag ghcr.io/${{ steps.repo.outputs.name }}/app:${{ steps.version.outputs.tag }} \
            ghcr.io/${{ steps.repo.outputs.name }}/app:${{ steps.find_pr.outputs.tag }}

      - name: Create and push Git tag
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git tag -a ${{ steps.version.outputs.tag }} -m "Release ${{ steps.version.outputs.tag }}"
          git push origin ${{ steps.version.outputs.tag }}

