name: Deploy - Coolify

on:
  push:
    branches:
      - main
  workflow_dispatch:

jobs:
  deploy:
    runs-on: ubuntu-latest
    env:
      COOLIFY_BASE_URL: ${{ secrets.COOLIFY_BASE_URL }}
      COOLIFY_API_TOKEN: ${{ secrets.COOLIFY_API_TOKEN }}
      COOLIFY_APPLICATION_ID: ${{ secrets.COOLIFY_APPLICATION_ID }}
      COOLIFY_DEPLOY_ENV: ${{ secrets.COOLIFY_DEPLOY_ENV }}
      DOCKER_COMPOSE_PATH: docker-compose.prod.yml
      ENV_FILE_PATH: deploy/.env
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Capture deployment context
        id: context
        run: |
          set -euo pipefail
          repo="${GITEA_REPOSITORY:-${GITHUB_REPOSITORY:-}}"
          if [ -z "$repo" ]; then
            repo="$(git remote get-url origin | sed 's#.*/\(.*\)\.git#\1#')"
          fi
          ref_name="${GITEA_REF_NAME:-${GITHUB_REF_NAME:-}}"
          full_ref="${GITEA_REF:-${GITHUB_REF:-}}"
          if [ -z "$ref_name" ] && [ -n "$full_ref" ]; then
            ref_name="${full_ref##*/}"
          fi
          if [ -z "$ref_name" ]; then
            ref_name="$(git rev-parse --abbrev-ref HEAD)"
          fi
          sha="${GITEA_SHA:-${GITHUB_SHA:-}}"
          if [ -z "$sha" ]; then
            sha="$(git rev-parse HEAD)"
          fi

          echo "repository=$repo" >> "$GITHUB_OUTPUT"
          echo "ref=${ref_name:-main}" >> "$GITHUB_OUTPUT"
          echo "sha=$sha" >> "$GITHUB_OUTPUT"

      - name: Prepare compose bundle
        run: |
          set -euo pipefail
          mkdir -p deploy
          cp "$DOCKER_COMPOSE_PATH" deploy/docker-compose.yml
          if [ -n "$COOLIFY_DEPLOY_ENV" ]; then
            printf '%s\n' "$COOLIFY_DEPLOY_ENV" > "$ENV_FILE_PATH"
          elif [ ! -f "$ENV_FILE_PATH" ]; then
            echo "::error::COOLIFY_DEPLOY_ENV secret not configured and deploy/.env missing" >&2
            exit 1
          fi

      - name: Validate Coolify secrets
        run: |
          set -euo pipefail
          missing=0
          for var in COOLIFY_BASE_URL COOLIFY_API_TOKEN COOLIFY_APPLICATION_ID; do
            if [ -z "${!var}" ]; then
              echo "::error::Missing required secret: $var"
              missing=1
            fi
          done
          if [ "$missing" -eq 1 ]; then
            exit 1
          fi

      - name: Trigger deployment via Coolify API
        env:
          HEAD_SHA: ${{ steps.context.outputs.sha }}
        run: |
          set -euo pipefail
          api_url="$COOLIFY_BASE_URL/api/v1/applications/${COOLIFY_APPLICATION_ID}/deploy"
          payload=$(jq -n --arg sha "$HEAD_SHA" '{ commitSha: $sha }')
          response=$(curl -sS -w '\n%{http_code}' \
            -X POST "$api_url" \
            -H "Authorization: Bearer $COOLIFY_API_TOKEN" \
            -H "Content-Type: application/json" \
            -d "$payload")
          body=$(echo "$response" | head -n -1)
          status=$(echo "$response" | tail -n1)
          echo "Deploy response status: $status"
          echo "$body"
          printf '%s' "$body" > deploy/coolify-response.json
          if [ "$status" -ge 400 ]; then
            echo "::error::Deployment request failed"
            exit 1
          fi

      - name: Upload deployment bundle
        if: always()
        uses: actions/upload-artifact@v3
        with:
          name: coolify-deploy-bundle
          path: |
            deploy/docker-compose.yml
            deploy/.env
            deploy/coolify-response.json
          if-no-files-found: warn
