name: CI - Production Readiness

on:
  push:
  pull_request:

jobs:
  verify:
    name: Verify
    runs-on: ubuntu-latest
    env:
      DATABASE_URL: "file:./.ci.sqlite"
      AUTH_SECRET: "whatsapp-inbox-ci-secret"
      NEXT_PUBLIC_APP_URL: "http://127.0.0.1:3000"
      APP_URL: "http://127.0.0.1:3000"
      OPS_BASE_URL: "http://127.0.0.1:3000"
      CAMPAIGN_RETRY_JOB_TOKEN: "ci-campaign-retry-token"
      HEALTHCHECK_TOKEN: "ci-health-token"
      WHATSAPP_WEBHOOK_VERIFY_TOKEN: "ci-verify-token"
      WHATSAPP_WEBHOOK_SECRET: "ci-webhook-secret"
      RETRY_WORKER_STALE_MINUTES: "15"
      WEBHOOK_FAILURE_RATE_THRESHOLD_PER_HOUR: "99"
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: 20

      - name: Install dependencies
        run: npm ci

      - name: Prepare database
        run: npm run db:deploy

      - name: Static verification
        run: npm run ci:verify

      - name: Start app
        run: npm run start -- --hostname 127.0.0.1 --port 3000 > /tmp/ci-app.log 2>&1 &

      - name: Run ops health checks
        run: |
          for i in $(seq 1 40); do
            if curl -fsS "http://127.0.0.1:3000/api/health?token=$HEALTHCHECK_TOKEN" >/dev/null; then
              break
            fi
            if [ "$i" -eq 40 ]; then
              echo "App not ready for health check"
              tail -n 120 /tmp/ci-app.log
              exit 1
            fi
            sleep 2
          done

          APP_URL=http://127.0.0.1:3000 \
          NEXT_PUBLIC_APP_URL=http://127.0.0.1:3000 \
          OPS_BASE_URL=http://127.0.0.1:3000 \
          HEALTHCHECK_TOKEN=$HEALTHCHECK_TOKEN \
          CAMPAIGN_RETRY_JOB_TOKEN=$CAMPAIGN_RETRY_JOB_TOKEN \
          npm run ops:healthcheck

          APP_URL=http://127.0.0.1:3000 \
          NEXT_PUBLIC_APP_URL=http://127.0.0.1:3000 \
          OPS_BASE_URL=http://127.0.0.1:3000 \
          HEALTHCHECK_TOKEN=$HEALTHCHECK_TOKEN \
          CAMPAIGN_RETRY_JOB_TOKEN=$CAMPAIGN_RETRY_JOB_TOKEN \
          npm run ops:readiness
      - name: Print app log on failure
        if: failure()
        run: tail -n 200 /tmp/ci-app.log
