name: Docker CI

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

env:
  REGISTRY: ghcr.io
  IMAGE_NAME_WEB: ghcr.io/${{ github.repository }}/web
  IMAGE_NAME_WORKER: ghcr.io/${{ github.repository }}/worker

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

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

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

      - name: Log in to GHCR
        if: github.event_name == 'push'
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract metadata (tags, labels) for Web
        id: meta-web
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.IMAGE_NAME_WEB }}
          tags: |
            type=ref,event=branch
            type=ref,event=pr
            type=sha,format=short
            latest

      - name: Build and Push Web Image
        uses: docker/build-push-action@v6
        with:
          context: .
          push: ${{ github.event_name == 'push' }}
          tags: ${{ steps.meta-web.outputs.tags }}
          labels: ${{ steps.meta-web.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Extract metadata (tags, labels) for Worker
        id: meta-worker
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.IMAGE_NAME_WORKER }}
          tags: |
            type=ref,event=branch
            type=ref,event=pr
            type=sha,format=short
            latest

      - name: Build and Push Worker Image
        uses: docker/build-push-action@v6
        with:
          context: .
          push: ${{ github.event_name == 'push' }}
          tags: ${{ steps.meta-worker.outputs.tags }}
          labels: ${{ steps.meta-worker.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
