name: Deploy to Coolify

on:
  workflow_call:
    inputs:
      environment:
        required: true
        type: string
      image:
        required: true
        type: string

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: ${{{{ inputs.environment }}}}
    steps:
      - name: Configure SSH
        run: |
          mkdir -p ~/.ssh
          echo "${{{{ secrets.COOLIFY_SSH_KEY }}}}" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519
          ssh-keyscan -H ${{{{ secrets.COOLIFY_SSH_HOST }}}} >> ~/.ssh/known_hosts

      - name: Trigger Coolify Deploy (via SSH — the Coolify API is not publicly exposed)
        run: |
          ssh -i ~/.ssh/id_ed25519 ${{{{ secrets.COOLIFY_SSH_USER }}}}@${{{{ secrets.COOLIFY_SSH_HOST }}}} \
            'T=$(cat ~/.coolify-token); curl -s -X GET -H "Authorization: Bearer $T" "http://localhost:8000/api/v1/deploy?uuid=${{{{ secrets.COOLIFY_APPLICATION_UUID }}}}"'

      - name: Health Check
        run: |
          sleep 30  # Wait for deployment
          curl --retry 10 --retry-delay 5 --retry-connrefused ${{{{ secrets.APP_URL }}}}/health
