name: Stripe Bootstrap

# Default-deny: scope GITHUB_TOKEN to read-only. The bootstrap script
# authenticates with STRIPE_SECRET_KEY and FLY_API_TOKEN secrets, not the
# GitHub token, so read-only is sufficient.
permissions: read-all

# Idempotent one-shot: creates Stripe products + prices + webhook endpoint
# matching gluecron's billing schema. Re-runnable. Propagates the
# STRIPE_SECRET_KEY and STRIPE_WEBHOOK_SECRET into Fly so the live site
# can authenticate calls and verify webhooks.
#
# Trigger manually via Actions tab → "Stripe Bootstrap" → Run workflow.
# Pick mode=test (default) before going live.

on:
  workflow_dispatch:
    inputs:
      mode:
        description: "test or live"
        type: choice
        options: [test, live]
        default: test

concurrency:
  group: stripe-bootstrap
  cancel-in-progress: false

jobs:
  bootstrap:
    name: Bootstrap Stripe
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: oven-sh/setup-bun@v1
        with:
          bun-version: latest

      - name: Install deps
        run: bun install --frozen-lockfile

      - name: Install flyctl
        run: |
          curl -fsSL https://github.com/superfly/flyctl/releases/download/v0.4.38/flyctl_0.4.38_Linux_x86_64.tar.gz -o /tmp/flyctl.tgz
          mkdir -p $HOME/.fly/bin
          tar -xzf /tmp/flyctl.tgz -C $HOME/.fly/bin
          echo "$HOME/.fly/bin" >> $GITHUB_PATH

      - name: Run Stripe bootstrap
        id: stripe
        env:
          STRIPE_SECRET_KEY: ${{ inputs.mode == 'live' && secrets.STRIPE_SECRET_KEY_LIVE || secrets.STRIPE_SECRET_KEY_TEST }}
          APP_BASE_URL: ${{ vars.APP_BASE_URL || 'https://gluecron.fly.dev' }}
        run: bun run scripts/stripe-bootstrap.ts

      - name: Propagate secrets to Fly
        if: steps.stripe.outputs.webhook_secret != ''
        env:
          FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN }}
          STRIPE_SECRET_KEY: ${{ inputs.mode == 'live' && secrets.STRIPE_SECRET_KEY_LIVE || secrets.STRIPE_SECRET_KEY_TEST }}
          WEBHOOK_SECRET: ${{ steps.stripe.outputs.webhook_secret }}
        run: |
          # CI env vars injected by GitHub Actions above — not hardcoded values. secrets-ok
          MODE="${{ inputs.mode }}"
          flyctl secrets set --app gluecron --stage \
            "STRIPE_SECRET_KEY=$STRIPE_SECRET_KEY" \
            "STRIPE_WEBHOOK_SECRET=$WEBHOOK_SECRET" \
            "STRIPE_MODE=$MODE"
          echo "Staged Stripe secrets onto Fly. They'll activate on next deploy."

      - name: Also re-run deploy to activate secrets
        if: steps.stripe.outputs.webhook_secret != ''
        env:
          FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN }}
        run: flyctl deploy --remote-only --app gluecron
