name: Deploy to Coolify
run-name: ${{ gitea.actor }} is executing Deploy to Coolify 🚀

on:
  workflow_dispatch:
  push:
    branches:
      - main

jobs:
  quality-assurance:
    name: Quality Assurance
    uses: ./.gitea/workflows/quality_assurance.yaml

  deploy:
    name: Deploy to Coolify
    runs-on: ubuntu-latest
    needs: quality-assurance
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Deploy to Coolify
        env:
          TG_BOT_TOKEN: ${{ secrets.TG_BOT_TOKEN }}
          COOLIFY_WEBHOOK_URL: ${{ secrets.COOLIFY_WEBHOOK_URL }}
          COOLIFY_UI_WEBHOOK_URL: ${{ secrets.COOLIFY_UI_WEBHOOK_URL }}
          COOLIFY_API_TOKEN: ${{ secrets.COOLIFY_API_TOKEN }}
        run: |
          echo "Deploying to Coolify..."
          if [ -z "$COOLIFY_WEBHOOK_URL" ]; then
            echo "Error: COOLIFY_WEBHOOK_URL environment variable not set"
            echo "Please set COOLIFY_WEBHOOK_URL in your environment or .env file"
            exit 1
          fi
          echo "Triggering Coolify deployment via webhook..."
          curl -X POST "$COOLIFY_WEBHOOK_URL" \
            -H "Content-Type: application/json" \
            -H "Authorization: Bearer $COOLIFY_API_TOKEN" \
            -d '{"source": "gitea", "branch": "main", "commit": "'$(git rev-parse HEAD)'"}' \
            --silent --show-error
          curl -X POST "$COOLIFY_UI_WEBHOOK_URL" \
            -H "Content-Type: application/json" \
            -H "Authorization: Bearer $COOLIFY_API_TOKEN" \
            -d '{"source": "gitea", "branch": "main", "commit": "'$(git rev-parse HEAD)'"}' \
            --silent --show-error
          echo "Coolify deployment triggered successfully! UI deployment triggered successfully!"

      # Step to run if deploy fails
      - name: Notify on Deploy Failure
        if: failure()
        env:
          TG_BOT_TOKEN: ${{ secrets.TG_BOT_TOKEN }}
        run: |
          curl --location "https://api.telegram.org/bot$TG_BOT_TOKEN/sendMessage" \
            --header 'Content-Type: application/json' \
            --data '{"chat_id": "-1002299691117", "message_thread_id": 7, "text": "[*Vertex CRM*](https://crm.vertexdc.com) Deploy to Coolify has FAILED", "parse_mode": "MarkdownV2"}'
