name: Set TNAASH Turnstile Secret on Portal Worker

on:
  workflow_dispatch:

jobs:
  set-secret:
    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 }}
      SITEKEY: "0x4AAAAAACxOvxLgEP9j1MgE"

    steps:
      - name: Fetch Turnstile widget secret key
        id: widget
        run: |
          RESULT=$(curl -sS "$CF_API/accounts/$ACCOUNT_ID/challenges/widgets/$SITEKEY" \
            -H "Authorization: Bearer $CF_TOKEN")
          SUCCESS=$(echo "$RESULT" | jq -r '.success')
          if [ "$SUCCESS" != "true" ]; then
            echo "Failed to fetch widget: $(echo "$RESULT" | jq -c '.errors')"
            exit 1
          fi
          SECRET=$(echo "$RESULT" | jq -r '.result.secret_key')
          echo "::add-mask::$SECRET"
          echo "secret=$SECRET" >> "$GITHUB_OUTPUT"
          echo "Widget found for sitekey $SITEKEY"

      - name: Set TURNSTILE_SECRET_KEY on cultscale-os worker
        run: |
          SECRET="${{ steps.widget.outputs.secret }}"
          RESULT=$(curl -sS -X PUT "$CF_API/accounts/$ACCOUNT_ID/workers/scripts/cultscale-os/secrets" \
            -H "Authorization: Bearer $CF_TOKEN" \
            -H "Content-Type: application/json" \
            -d "{\"name\":\"TURNSTILE_SECRET_KEY\",\"text\":\"$SECRET\",\"type\":\"secret_text\"}")
          SUCCESS=$(echo "$RESULT" | jq -r '.success')
          NAME=$(echo "$RESULT" | jq -r '.result.name // empty')
          echo "Set secret success: $SUCCESS — $NAME"
          if [ "$SUCCESS" != "true" ]; then
            echo "$RESULT" | jq '.errors'
            exit 1
          fi

      - name: Summary
        run: |
          echo "### Turnstile Server-Side Verification" >> "$GITHUB_STEP_SUMMARY"
          echo "- \`TURNSTILE_SECRET_KEY\` set on \`cultscale-os\` worker" >> "$GITHUB_STEP_SUMMARY"
          echo "- Widget: \`$SITEKEY\` (tnaash.mov)" >> "$GITHUB_STEP_SUMMARY"
          echo "- Server-side verification is now active for TNAASH form submissions" >> "$GITHUB_STEP_SUMMARY"
