name: API Docker Image

on:
  pull_request:
    branches: [main, develop]
    paths:
      - "apps/api/**"
      - ".github/workflows/api-docker-image.yml"
  push:
    branches: [main]
    paths:
      - "apps/api/**"
      - ".github/workflows/api-docker-image.yml"
  workflow_dispatch:

concurrency:
  group: api-docker-${{ github.ref }}
  cancel-in-progress: true

jobs:
  build-and-publish:
    name: Build API Docker Image
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

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

      - name: Check Dockerfile
        id: dockerfile
        run: |
          if [ -f apps/api/Dockerfile ]; then
            echo "exists=true" >> "$GITHUB_OUTPUT"
          else
            echo "exists=false" >> "$GITHUB_OUTPUT"
          fi

      - name: Setup Docker Buildx
        if: steps.dockerfile.outputs.exists == 'true'
        uses: docker/setup-buildx-action@v3

      - name: Login to GitHub Container Registry
        if: steps.dockerfile.outputs.exists == 'true' && github.event_name == 'push' && github.ref == 'refs/heads/main'
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build (PR/manual) or Build and Push (main)
        if: steps.dockerfile.outputs.exists == 'true'
        uses: docker/build-push-action@v6
        with:
          context: ./apps/api
          file: ./apps/api/Dockerfile
          push: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }}
          tags: |
            ghcr.io/${{ github.repository }}/api:${{ github.sha }}
            ghcr.io/${{ github.repository }}/api:latest

      - name: Skip notice
        if: steps.dockerfile.outputs.exists != 'true'
        run: echo "apps/api/Dockerfile not found, skip docker build."
