## github action to check deployment success
## curl the deployment url and check for 200 status
## deployment url will be of the form chatwoot-pr-<pr_number>.herokuapp.com
name: Deploy Check

on:
  pull_request:

# If two pushes happen within a short time in the same PR, cancel the run of the oldest push
concurrency:
  group: pr-${{ github.workflow }}-${{ github.head_ref }}
  cancel-in-progress: true

jobs:
  deployment_check:
    name: Check Deployment
    runs-on: [self-hosted, oracle-arm]
    steps:
      - name: Print Deployment URL
        run: echo "https://chatwoot-pr-${{ github.event.pull_request.number }}.herokuapp.com"
      - name: Check Deployment Status
        run: |
          max_attempts=15
          attempt=1
          status_code=0
          echo "Checking review app status..."
          while [ $attempt -le $max_attempts ]; do
            response=$(curl -s -o /dev/null -w "%{http_code}" https://chatwoot-pr-${{ github.event.pull_request.number }}.herokuapp.com/api)
            status_code=$(echo $response | head -n   1)
            if [ $status_code -eq   200 ]; then
              body=$(curl -s https://chatwoot-pr-${{ github.event.pull_request.number }}.herokuapp.com/api)
              # Check for required fields using grep to avoid jq dependency on self-hosted runners
              if echo "$body" | grep -q '"version"' && echo "$body" | grep -q '"timestamp"' && echo "$body" | grep -q '"queue_services":"ok"' && echo "$body" | grep -q '"data_services":"ok"'; then
                echo "Deployment successful"
                exit 0
              else
                echo "Deployment status healthy but services not ready, retrying in 30 seconds... (Attempt $attempt/$max_attempts)"
                sleep 30
                attempt=$((attempt + 1))
              fi
            else
              echo "Waiting for review app to be ready, retrying in 30 seconds... (Attempt $attempt/$max_attempts)"
              sleep 30
              attempt=$((attempt + 1))
            fi
          done
          echo "Deployment check timed out after $max_attempts attempts"
          exit 1
