name: Build Docker Images

on:
  push:
    branches: [main]
    paths:
      - 'packages/backend/**'
      - 'packages/frontend/**'
      - 'Dockerfile*'
  workflow_dispatch:

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

    steps:
      - uses: actions/checkout@v4

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

      - name: Login to Container Registry
        uses: docker/login-action@v3
        with:
          registry: {{ registry }}
          username: ${{ '{{' }} github.actor {{ '}}' }}
          password: ${{ '{{' }} secrets.GITHUB_TOKEN {{ '}}' }}

      - name: Build and push backend
        uses: docker/build-push-action@v6
        with:
          context: .
          file: Dockerfile.backend.prod
          push: true
          tags: |
            {{ registry }}/${{ '{{' }} github.repository {{ '}}' }}-backend:${{ '{{' }} github.sha {{ '}}' }}
            {{ registry }}/${{ '{{' }} github.repository {{ '}}' }}-backend:latest
          {% if platforms %}
          platforms: {{ platforms | join(",") }}
          {% endif %}
          {% for key, value in build_args.items() %}
          build-args: |
            {{ key }}={{ value }}
          {% endfor %}
          {% if cache_from %}
          cache-from: {{ cache_from }}
          {% else %}
          cache-from: type=gha
          {% endif %}
          cache-to: type=gha,mode=max

      - name: Build and push frontend
        uses: docker/build-push-action@v6
        if: hashFiles('Dockerfile.frontend.prod') != ''
        with:
          context: .
          file: Dockerfile.frontend.prod
          push: true
          tags: |
            {{ registry }}/${{ '{{' }} github.repository {{ '}}' }}-frontend:${{ '{{' }} github.sha {{ '}}' }}
            {{ registry }}/${{ '{{' }} github.repository {{ '}}' }}-frontend:latest
          {% if platforms %}
          platforms: {{ platforms | join(",") }}
          {% endif %}
          {% if cache_from %}
          cache-from: {{ cache_from }}
          {% else %}
          cache-from: type=gha
          {% endif %}
          cache-to: type=gha,mode=max
