name: Build Docker Images (AWS ECR)

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

env:
  AWS_REGION: {{ aws_region }}
  ECR_REPOSITORY: {{ ecr_repository }}

jobs:
  build-and-push:
    name: Build and Push to ECR
    runs-on: ubuntu-latest
    permissions:
      id-token: write
      contents: read

    steps:
      - uses: actions/checkout@v4

      - name: Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@v4
        with:
          aws-access-key-id: ${{ '{{' }} secrets.AWS_ACCESS_KEY_ID {{ '}}' }}
          aws-secret-access-key: ${{ '{{' }} secrets.AWS_SECRET_ACCESS_KEY {{ '}}' }}
          aws-region: ${{ '{{' }} env.AWS_REGION {{ '}}' }}

      - name: Login to Amazon ECR
        id: login-ecr
        uses: aws-actions/amazon-ecr-login@v2

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

      - name: Build and push backend
        uses: docker/build-push-action@v6
        with:
          context: .
          file: Dockerfile.backend.prod
          push: true
          tags: |
            ${{ '{{' }} steps.login-ecr.outputs.registry {{ '}}' }}/${{ '{{' }} env.ECR_REPOSITORY {{ '}}' }}-backend:${{ '{{' }} github.sha {{ '}}' }}
            ${{ '{{' }} steps.login-ecr.outputs.registry {{ '}}' }}/${{ '{{' }} env.ECR_REPOSITORY {{ '}}' }}-backend:latest
          {% if platforms %}
          platforms: {{ platforms | join(",") }}
          {% endif %}
          {% for key, value in build_args.items() %}
          build-args: |
            {{ key }}={{ value }}
          {% endfor %}
          cache-from: type=gha
          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: |
            ${{ '{{' }} steps.login-ecr.outputs.registry {{ '}}' }}/${{ '{{' }} env.ECR_REPOSITORY {{ '}}' }}-frontend:${{ '{{' }} github.sha {{ '}}' }}
            ${{ '{{' }} steps.login-ecr.outputs.registry {{ '}}' }}/${{ '{{' }} env.ECR_REPOSITORY {{ '}}' }}-frontend:latest
          {% if platforms %}
          platforms: {{ platforms | join(",") }}
          {% endif %}
          cache-from: type=gha
          cache-to: type=gha,mode=max
