name: Build App Candidate

on:
  workflow_dispatch:

jobs:
  build-and-push-app:
    name: Build & Push App
    runs-on: easynode-debian
    permissions:
      contents: read
      packages: write

    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          ref: ${{ github.ref }}

      - name: Set up Docker Buildx
        run: docker buildx inspect --bootstrap

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

      - name: Extract metadata for Docker
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: rmcampos/tasknote-app
          tags: |
            type=raw,value=candidate

      - 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: Build and push Docker image
        uses: docker/build-push-action@v5
        with:
          context: ./client
          push: true
          tags: |
            ${{ steps.meta.outputs.tags }}
            rmcampos/tasknote-app:${{ steps.version.outputs.tag }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=registry,ref=rmcampos/tasknote-app:buildcache
          cache-to: type=registry,ref=rmcampos/tasknote-app:buildcache,mode=max
          build-args: |
            VITE_BUILD=${{ steps.version.outputs.tag }}

      - name: Log pushed images
        run: |
          echo "Pushed images:"
          echo "  rmcampos/tasknote-app:candidate"
          echo "  rmcampos/tasknote-app:${{ steps.version.outputs.tag }}"