name: Build and Push to GHCR (multi-arch)

on:
  push:
    branches:
      - chatwoot-jasmine
  workflow_dispatch:

env:
  IMAGE_NAME: ghcr.io/rodribm10/chatwoot-jasmine

jobs:
  build:
    strategy:
      fail-fast: false
      matrix:
        include:
          - platform: linux/amd64
            runner: ubuntu-latest
          - platform: linux/arm64
            runner: ubuntu-22.04-arm
    runs-on: ${{ matrix.runner }}
    permissions:
      contents: read
      packages: write

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

      - name: Prepare
        run: |
          platform="${{ matrix.platform }}"
          echo "PLATFORM_PAIR=${platform//\//-}" >> "$GITHUB_ENV"

      # (Opcional) Se você quiser tags dinâmicas por branch/commit
      - name: Set tag
        run: |
          echo "TAG=latest" >> "$GITHUB_ENV"

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

      # QEMU só é necessário se você for cross-build.
      # Como estamos usando runner arm nativo, não é obrigatório,
      # mas deixar não costuma atrapalhar.
      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3

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

      - name: Build and push by digest
        id: build
        uses: docker/build-push-action@v6
        with:
          context: .
          file: ./docker/Dockerfile
          platforms: ${{ matrix.platform }}
          push: true
          build-args: |
            RAILS_ENV=production
            NODE_ENV=production

          # Publica por digest e deixa o merge job criar a tag multi-arch final
          outputs: type=image,name=${{ env.IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true

          # Cache (MUITO recomendado pra não estourar 6h)
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Export digest
        run: |
          mkdir -p "${{ runner.temp }}/digests"
          digest="${{ steps.build.outputs.digest }}"
          touch "${{ runner.temp }}/digests/${digest#sha256:}"

      - name: Upload digest
        uses: actions/upload-artifact@v4
        with:
          name: digests-${{ env.PLATFORM_PAIR }}
          path: ${{ runner.temp }}/digests/*
          if-no-files-found: error
          retention-days: 1

  merge:
    runs-on: ubuntu-latest
    needs: [build]
    permissions:
      packages: write

    steps:
      - name: Download digests
        uses: actions/download-artifact@v4
        with:
          path: ${{ runner.temp }}/digests
          pattern: digests-*
          merge-multiple: true

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

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

      - name: Create manifest list and push
        working-directory: ${{ runner.temp }}/digests
        run: |
          TAG="${{ env.IMAGE_NAME }}:latest"

          docker buildx imagetools create -t "$TAG" \
            $(printf '${{ env.IMAGE_NAME }}@sha256:%s ' *)

      - name: Inspect image
        run: |
          docker buildx imagetools inspect "${{ env.IMAGE_NAME }}:latest"
