name: Deploy to Dokploy

# Auto-deploy on push to main (re-enabled 2026-07-19 by flndrn request).
# Also runnable by hand via workflow_dispatch.
#
# Secrets required: DOKPLOY_WEBHOOK_URL + DOKPLOY_API_KEY
# Dokploy compose autoDeploy should also be true so git webhooks / Actions both work.

on:
  push:
    branches: [main]
  workflow_dispatch:
    inputs:
      reason:
        description: 'Why deploy? (note only)'
        required: false
        default: 'manual deploy'

jobs:
  deploy:
    name: Deploy to dokploy
    runs-on: ubuntu-latest
    steps:
      - name: Trigger Dokploy deploy
        env:
          DOKPLOY_WEBHOOK_URL: ${{ secrets.DOKPLOY_WEBHOOK_URL }}
          DOKPLOY_API_KEY: ${{ secrets.DOKPLOY_API_KEY }}
          GIT_REF: refs/heads/main
          REPO_FULL: ${{ github.repository }}
          REPO_NAME: ${{ github.event.repository.name }}
          OWNER: ${{ github.repository_owner }}
          SHA: ${{ github.sha }}
          REASON: ${{ github.event.inputs.reason || github.event.head_commit.message || 'push' }}
        run: |
          set -euo pipefail
          echo "Deploy trigger. Reason: ${REASON:-none}"
          if [ -z "${DOKPLOY_WEBHOOK_URL:-}" ] || [ -z "${DOKPLOY_API_KEY:-}" ]; then
            echo "::error::Missing DOKPLOY_WEBHOOK_URL or DOKPLOY_API_KEY secrets."
            exit 1
          fi
          payload=$(printf '%s' "{
            \"ref\": \"${GIT_REF}\",
            \"after\": \"${SHA}\",
            \"repository\": {
              \"name\": \"${REPO_NAME}\",
              \"full_name\": \"${REPO_FULL}\",
              \"default_branch\": \"main\",
              \"clone_url\": \"https://github.com/${REPO_FULL}.git\",
              \"owner\": { \"login\": \"${OWNER}\", \"name\": \"${OWNER}\" }
            }
          }")
          http_code=$(curl -sS -o /tmp/dokploy-response.txt -w "%{http_code}" \
            -X POST "${DOKPLOY_WEBHOOK_URL}" \
            -H "Authorization: Bearer ${DOKPLOY_API_KEY}" \
            -H "Content-Type: application/json" \
            -H "X-GitHub-Event: push" \
            -d "${payload}")
          echo "Dokploy HTTP status: ${http_code}"
          cat /tmp/dokploy-response.txt || true
          case "${http_code}" in
            200|201|202|204) echo "Deploy trigger accepted." ;;
            *) echo "::error::Dokploy rejected deploy"; exit 1 ;;
          esac
