name: Setup TNAASH Cloudflare Services

on:
  workflow_dispatch:

permissions:
  actions: write
  contents: read

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 Turnstile widget
        id: turnstile
        run: |
          LIST_RESULT=$(curl -sS "$CF_API/accounts/$ACCOUNT_ID/challenges/widgets" \
            -H "Authorization: Bearer $CF_TOKEN" || true)
          LIST_SUCCESS=$(echo "$LIST_RESULT" | jq -r '.success // empty' 2>/dev/null || true)

          if [ "$LIST_SUCCESS" != "true" ]; then
            ERROR_MSG=$(echo "$LIST_RESULT" | jq -r '.errors[0].message // "Turnstile API unavailable for this token"' 2>/dev/null || echo "Turnstile API unavailable for this token")
            echo "Turnstile API unavailable: $ERROR_MSG"
            echo "sitekey=" >> "$GITHUB_OUTPUT"
            echo "manual_note=Cloudflare token could not access the Turnstile API: $ERROR_MSG" >> "$GITHUB_OUTPUT"
            exit 0
          fi

          EXISTING=$(echo "$LIST_RESULT" \
            | jq -r '.result // [] | .[] | select(any(.domains[]; . == "tnaash.mov")) | .sitekey' 2>/dev/null | head -1 || true)

          if [ -n "$EXISTING" ] && [ "$EXISTING" != "null" ]; then
            echo "Turnstile widget already exists: $EXISTING"
            echo "sitekey=$EXISTING" >> "$GITHUB_OUTPUT"
            echo "manual_note=" >> "$GITHUB_OUTPUT"
          else
            RESULT=$(curl -sS -X POST "$CF_API/accounts/$ACCOUNT_ID/challenges/widgets" \
              -H "Authorization: Bearer $CF_TOKEN" \
              -H "Content-Type: application/json" \
              -d '{"name":"tnaash.mov","domains":["tnaash.mov","tnaash-web.pages.dev"],"mode":"managed","bot_fight_mode":false}' || true)
            CREATE_SUCCESS=$(echo "$RESULT" | jq -r '.success // empty' 2>/dev/null || true)

            if [ "$CREATE_SUCCESS" != "true" ]; then
              ERROR_MSG=$(echo "$RESULT" | jq -r '.errors[0].message // "Turnstile widget creation failed"' 2>/dev/null || echo "Turnstile widget creation failed")
              ERROR_CODE=$(echo "$RESULT" | jq -r '.errors[0].code // "unknown"' 2>/dev/null || echo "unknown")
              echo "Turnstile widget creation failed: $ERROR_MSG (code: $ERROR_CODE)"
              echo "Full response: $(echo "$RESULT" | jq -c '{success,errors,messages}' 2>/dev/null || echo "$RESULT")"
              echo "sitekey=" >> "$GITHUB_OUTPUT"
              echo "manual_note=Cloudflare token could not create the Turnstile widget: $ERROR_MSG" >> "$GITHUB_OUTPUT"
              exit 0
            fi

            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"
            echo "::add-mask::$SECRET"
            echo "secret=$SECRET" >> "$GITHUB_OUTPUT"
            echo "manual_note=" >> "$GITHUB_OUTPUT"
          fi

      - name: Set PUBLIC_TURNSTILE_SITE_KEY on tnaash-web Pages project
        if: steps.turnstile.outputs.sitekey != ''
        run: |
          TURNSTILE_SITEKEY="${{ steps.turnstile.outputs.sitekey }}"

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

          RESULT=$(curl -sf -X PATCH "$CF_API/accounts/$ACCOUNT_ID/pages/projects/tnaash-web" \
            -H "Authorization: Bearer $CF_TOKEN" \
            -H "Content-Type: application/json" \
            -d "{
              \"deployment_configs\": {
                \"production\": {
                  \"env_vars\": {
                    \"PUBLIC_TURNSTILE_SITE_KEY\": {\"value\": \"$TURNSTILE_SITEKEY\"}
                  }
                },
                \"preview\": {
                  \"env_vars\": {
                    \"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 TNAASH redeploy
        if: steps.turnstile.outputs.sitekey != ''
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          gh workflow run deploy-tnaash.yml \
            --repo ${{ github.repository }} \
            --ref main
          echo "Redeploy triggered — tnaash-web will rebuild with the Turnstile site key baked in"

      - name: Summary
        run: |
          echo "### TNAASH Cloudflare Services" >> "$GITHUB_STEP_SUMMARY"
          if [ -n "${{ steps.turnstile.outputs.sitekey }}" ]; then
            echo "- Turnstile sitekey \`${{ steps.turnstile.outputs.sitekey }}\` set on \`tnaash-web\`" >> "$GITHUB_STEP_SUMMARY"
            echo "- Domains: \`tnaash.mov\`, \`tnaash-web.pages.dev\`" >> "$GITHUB_STEP_SUMMARY"
            echo "- Redeploy triggered for \`deploy-tnaash.yml\`" >> "$GITHUB_STEP_SUMMARY"
            echo "" >> "$GITHUB_STEP_SUMMARY"
            echo "> **Next:** Set \`TURNSTILE_SECRET_KEY\` as a Workers secret on \`cultscale-os\` for server-side verification:" >> "$GITHUB_STEP_SUMMARY"
            echo "> \`wrangler secret put TURNSTILE_SECRET_KEY --name cultscale-os\`" >> "$GITHUB_STEP_SUMMARY"
            echo "> The secret key is visible in the Cloudflare Turnstile dashboard under the widget for tnaash.mov." >> "$GITHUB_STEP_SUMMARY"
          else
            echo "- Turnstile setup needs manual follow-up." >> "$GITHUB_STEP_SUMMARY"
            echo "- ${{ steps.turnstile.outputs.manual_note }}" >> "$GITHUB_STEP_SUMMARY"
            echo "- After creating the widget manually, set \`PUBLIC_TURNSTILE_SITE_KEY\` on \`tnaash-web\` and rerun this workflow." >> "$GITHUB_STEP_SUMMARY"
          fi
