name: Build and Push Multi-Arch Docker Image

on:
  push:
    branches:
      - main
      - dev

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 GitHub Container Registry
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Determine image tag and branch
        id: set-tag-branch
        run: |
          if [[ "${{ github.ref }}" == "refs/heads/main" ]]; then
            echo "TAG=latest" >> $GITHUB_ENV
            echo "BRANCH=main" >> $GITHUB_ENV
          elif [[ "${{ github.ref }}" == "refs/heads/dev" ]]; then
            echo "TAG=dev" >> $GITHUB_ENV
            echo "BRANCH=dev" >> $GITHUB_ENV
          fi

      - name: Convert repository name to lowercase
        run: echo "REPO_NAME=$(echo '${{ github.repository }}' | tr '[:upper:]' '[:lower:]')" >> $GITHUB_ENV

      - name: Build and push Docker image
        uses: docker/build-push-action@v5
        with:
          context: docker
          file: docker/Dockerfile
          push: true
          platforms: linux/amd64,linux/arm64
          build-args: |
            BRANCH=${{ env.BRANCH }}
            REPO_URL=https://github.com/${{ github.repository }}
          tags: |
            ghcr.io/${{ env.REPO_NAME }}:${{ env.TAG }}
            ghcr.io/${{ env.REPO_NAME }}:${{ github.sha }}
