name: Build and Push Container Image

on:
  push:
    branches:
      - main
    paths-ignore:
      - "deploy/**"
env:
  REGISTRY: reg.milasholsting.dk
  IMAGE_NAME: apps/mal

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3
        with:
          config-inline: |
            [registry."reg.milasholsting.dk"]
              http = false
              insecure = true

      - name: Log in to the Container registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ secrets.REGISTRY_USER }}
          password: ${{ secrets.REGISTRY_PASSWORD }}

      - name: Extract metadata (tags, labels) for Docker
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
          tags: |
            type=sha,prefix=sha-,format=short
            type=raw,value=latest

      - name: Build and push Docker image
        uses: docker/build-push-action@v5
        with:
          context: .
          file: ./Dockerfile
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Update Kustomize
        run: |
          IMAGE_TAG=$(echo '${{ steps.meta.outputs.json }}' | jq -r '.tags[] | select(startswith("reg.milasholsting.dk/apps/mal:sha-"))' | cut -d: -f2)

          echo "Targeting Tag: $IMAGE_TAG"

          cd deploy/overlays/production
          kustomize edit set image main=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:$IMAGE_TAG

      - name: Commit and Push Change
        run: |
          git config user.name "Gitea Action"
          git config user.email "actions@gitea.io"

          git add deploy/overlays/production/kustomization.yaml

          if git diff --staged --quiet; then
            echo "No changes to commit"
          else
            git commit -m "chore(deploy): update image to ${{ steps.meta.outputs.version }}"
            git push origin main
          fi
