name: Build and Push Docker Images

on:
  push:
    branches:
      - main
    tags:
      - 'v*'
  pull_request:
    branches:
      - main
  workflow_dispatch:
    inputs:
      push:
        description: Push images to registry
        required: false
        type: boolean
        default: false

env:
  REGISTRY: ghcr.io

permissions:
  contents: read
  packages: write

jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        image: [backend, frontend]
    steps:
      - name: Checkout repository
        uses: actions/checkout@v5

      - name: Log in to container registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.repository_owner }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3

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

      - name: Extract metadata (tags, labels)
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.REGISTRY }}/${{ github.repository }}-${{ matrix.image }}
          tags: |
            type=ref,event=pr
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=semver,pattern={{major}}
            type=edge,branch=main

      - name: Build and push ${{ matrix.image }} image
        uses: docker/build-push-action@v6
        with:
          context: .
          file: docker/${{ matrix.image }}.Dockerfile
          platforms: linux/amd64,linux/arm64
          # Push if:
          # - Event is not workflow_dispatch OR input 'push' is true
          # AND
          # - Event is not pull_request OR the PR is from the same repository (to avoid pushing from forks)
          push: ${{ (github.event_name != 'workflow_dispatch' || inputs.push == 'true') && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) }}
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha,scope=${{ matrix.image }}
          cache-to: type=gha,mode=max,scope=${{ matrix.image }}
