name: Setup MICHA Cloudflare Services

on:
  workflow_dispatch:

jobs:
  setup:
    runs-on: ubuntu-latest
    env:
      CF_API: https://api.cloudflare.com/client/v4
      ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
      CF_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}

    steps:
      - name: Create or get CF Web Analytics site
        id: analytics
        run: |
          # Check if site already exists
          EXISTING=$(curl -sf "$CF_API/accounts/$ACCOUNT_ID/web_analytics/sites" \
            -H "Authorization: Bearer $CF_TOKEN" \
            | jq -r '.result // [] | .[] | select(.host == "michapp.org") | .tag' 2>/dev/null || true)

          if [ -n "$EXISTING" ] && [ "$EXISTING" != "null" ]; then
            echo "Analytics site already exists: $EXISTING"
            echo "token=$EXISTING" >> "$GITHUB_OUTPUT"
          else
            RESULT=$(curl -sf -X POST "$CF_API/accounts/$ACCOUNT_ID/web_analytics/sites" \
              -H "Authorization: Bearer $CF_TOKEN" \
              -H "Content-Type: application/json" \
              -d '{"host":"michapp.org","auto_install":false}')
            TAG=$(echo "$RESULT" | jq -r '.result.tag')
            echo "Created analytics site: $TAG"
            echo "token=$TAG" >> "$GITHUB_OUTPUT"
          fi

      - name: Create or get Turnstile widget
        id: turnstile
        run: |
          # Check if a widget for michapp.org already exists
          EXISTING=$(curl -sf "$CF_API/accounts/$ACCOUNT_ID/challenges/widgets" \
            -H "Authorization: Bearer $CF_TOKEN" \
            | jq -r '.result // [] | .[] | select(any(.domains[]; . == "michapp.org")) | .sitekey' 2>/dev/null | head -1 || true)

          if [ -n "$EXISTING" ] && [ "$EXISTING" != "null" ]; then
            echo "Turnstile widget already exists: $EXISTING"
            echo "sitekey=$EXISTING" >> "$GITHUB_OUTPUT"
          else
            RESULT=$(curl -sf -X POST "$CF_API/accounts/$ACCOUNT_ID/challenges/widgets" \
              -H "Authorization: Bearer $CF_TOKEN" \
              -H "Content-Type: application/json" \
              -d '{"name":"michapp.org","domains":["michapp.org"],"mode":"managed","bot_fight_mode":false}')
            SITEKEY=$(echo "$RESULT" | jq -r '.result.sitekey')
            SECRET=$(echo "$RESULT" | jq -r '.result.secret_key')
            echo "Created Turnstile widget sitekey: $SITEKEY"
            echo "sitekey=$SITEKEY" >> "$GITHUB_OUTPUT"
            # Mask the secret key in logs
            echo "::add-mask::$SECRET"
            echo "secret=$SECRET" >> "$GITHUB_OUTPUT"
          fi

      - name: Set CF Pages environment variables on micha-web
        run: |
          ANALYTICS_TOKEN="${{ steps.analytics.outputs.token }}"
          TURNSTILE_SITEKEY="${{ steps.turnstile.outputs.sitekey }}"

          if [ -z "$ANALYTICS_TOKEN" ] || [ -z "$TURNSTILE_SITEKEY" ]; then
            echo "ERROR: Missing token or sitekey — aborting"
            exit 1
          fi

          RESULT=$(curl -sf -X PATCH "$CF_API/accounts/$ACCOUNT_ID/pages/projects/micha-web" \
            -H "Authorization: Bearer $CF_TOKEN" \
            -H "Content-Type: application/json" \
            -d "{
              \"deployment_configs\": {
                \"production\": {
                  \"env_vars\": {
                    \"CF_ANALYTICS_TOKEN\": {\"value\": \"$ANALYTICS_TOKEN\"},
                    \"PUBLIC_TURNSTILE_SITE_KEY\": {\"value\": \"$TURNSTILE_SITEKEY\"}
                  }
                },
                \"preview\": {
                  \"env_vars\": {
                    \"CF_ANALYTICS_TOKEN\": {\"value\": \"$ANALYTICS_TOKEN\"},
                    \"PUBLIC_TURNSTILE_SITE_KEY\": {\"value\": \"$TURNSTILE_SITEKEY\"}
                  }
                }
              }
            }")

          SUCCESS=$(echo "$RESULT" | jq -r '.success')
          echo "Pages env vars update success: $SUCCESS"
          if [ "$SUCCESS" != "true" ]; then
            echo "$RESULT" | jq '.errors'
            exit 1
          fi

      - name: Trigger MICHA redeploy
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          gh workflow run deploy-micha.yml \
            --repo ${{ github.repository }} \
            --ref main
          echo "Redeploy triggered — micha-web will rebuild with new env vars"

      - name: Summary
        run: |
          echo "### MICHA Cloudflare Services" >> "$GITHUB_STEP_SUMMARY"
          echo "- CF Web Analytics token set on \`micha-web\`" >> "$GITHUB_STEP_SUMMARY"
          echo "- Turnstile sitekey \`${{ steps.turnstile.outputs.sitekey }}\` set on \`micha-web\`" >> "$GITHUB_STEP_SUMMARY"
          echo "- Redeploy triggered — Turnstile widget and analytics beacon will be live" >> "$GITHUB_STEP_SUMMARY"
          echo "" >> "$GITHUB_STEP_SUMMARY"
          echo "> **Turnstile secret key** (for portal server-side verification): retrieve from CF dashboard → Turnstile → michapp.org widget" >> "$GITHUB_STEP_SUMMARY"
