name: Build and deploy Worker

on:
  push:
    branches:
      - main

permissions:
  contents: read
  packages: write

jobs:
  build:
    runs-on: builder
    env:
      SERVICE_NAME: worker
      IMAGE_SHA: gitea.dsrptlab.com/mapflow/worker:${{ github.sha }}
      IMAGE_LATEST: gitea.dsrptlab.com/mapflow/worker:latest
    steps:
      - uses: actions/checkout@v4

      - name: Build and push image
        run: |
          set -euo pipefail
          for attempt in 1 2 3; do
            if docker build --provenance=false --tag "$IMAGE_SHA" --tag "$IMAGE_LATEST" . &&
              docker push "$IMAGE_SHA" &&
              docker push "$IMAGE_LATEST"; then
              docker image rm -f "$IMAGE_SHA" "$IMAGE_LATEST"
              exit 0
            fi
            sleep "$((attempt * 10))"
          done
          exit 1

      - name: Skip stale deployment
        run: |
          set -euo pipefail
          latest_sha="$(git ls-remote origin refs/heads/main | awk '{print $1}')"
          if [ "$latest_sha" = "${GITHUB_SHA}" ]; then
            touch .deploy-current
          else
            echo "A newer main commit exists: $latest_sha. Skipping deploy for ${GITHUB_SHA}."
          fi

      - name: Trigger Dokploy deploy webhook
        run: |
          set -euo pipefail
          [ -f .deploy-current ] || exit 0
          payload=$(cat <<JSON
          {"ref":"refs/heads/main","after":"$GITHUB_SHA","commits":[{"id":"$GITHUB_SHA","message":"$SERVICE_NAME #${GITHUB_RUN_NUMBER:-0} ${GITHUB_SHA:0:7}","modified":["Dockerfile"]}]}
          JSON
          )
          response_file="$(mktemp)"
          status_code="$(curl -sS -o "$response_file" -w "%{http_code}" -X POST "${{ secrets.DOKPLOY_DEPLOY_WEBHOOK }}" \
            -H "x-gitea-event: push" \
            -H "Content-Type: application/json" \
            -d "$payload")"
          cat "$response_file"
          [ "$status_code" = "200" ]
