# scripts/setup-stripe.sh
#!/usr/bin/env bash
# Setup wizard for Stripe — prints the steps, validates env vars, and
# offers a one-shot smoke test against your live server.
#
# Pricing model: each paid plan has a monthly AND annual Stripe price
# (annual ≈ 2 months free). Agency is per-seat — quantity on the
# subscription scales team-member seats.
#
# Usage:
#   bash scripts/setup-stripe.sh          # interactive
#   bash scripts/setup-stripe.sh --check  # just validate env vars, no prompts
#   bash scripts/setup-stripe.sh --test   # validate + run end-to-end test against server
set -e

CYAN='\033[0;36m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; RED='\033[0;31m'; NC='\033[0m'
hr() { printf '%s\n' "----------------------------------------------------------------"; }

printf "\n${CYAN}Stripe setup for NCII Shield${NC}\n"
hr
printf "The backend is fully wired. You just need to:\n"
printf "  1. Create products + prices in the Stripe Dashboard\n"
printf "  2. Create a webhook endpoint in the Dashboard\n"
printf "  3. Paste the keys + ids into .env, then restart\n"
hr

# Load .env if present (using node to avoid bash ! history-expansion issues)
if [ -f .env ]; then
  while IFS='=' read -r key value; do
    case "$key" in
      ''|\#*) continue ;;  # skip blanks/comments
      STRIPE_*) export "$key"="$value" ;;
    esac
  done < .env
  printf "${GREEN}Loaded .env${NC}\n\n"
fi

# 1) Status report
printf "${YELLOW}Current env status:${NC}\n"
report() {
  local name="$1" desc="$2" good="$3"
  local v="${!name:-}"
  if [ -z "$v" ] || echo "$v" | grep -qE '_xxx$|sk_test_dummy'; then
    printf "  ${RED}MISSING${NC}  %-32s  %s\n" "$name" "$desc"
    GOOD=0
  else
    local masked="${v:0:10}...${v: -4}"
    if [ "$good" = "live" ] && echo "$v" | grep -q '^sk_live_'; then
      printf "  ${GREEN}LIVE   ${NC}  %-32s  %s\n" "$name" "$masked"
    elif [ "$good" = "test" ] && echo "$v" | grep -q '^sk_test_'; then
      printf "  ${GREEN}TEST   ${NC}  %-32s  %s\n" "$name" "$masked"
    else
      printf "  ${YELLOW}?      ${NC}  %-32s  %s\n" "$name" "$masked"
    fi
  fi
}
GOOD=1
report STRIPE_SECRET_KEY              "Secret API key (sk_test_... or sk_live_...)"  "test"
report STRIPE_PUBLISHABLE_KEY         "Publishable key (pk_test_... or pk_live_...)" "test"
report STRIPE_WEBHOOK_SECRET          "Webhook signing secret (whsec_...)"           "test"
report STRIPE_PRICE_STANDARD          "Standard — monthly  (\$29 / mo)"              "test"
report STRIPE_PRICE_STANDARD_ANNUAL   "Standard — annual   (\$290 / yr)"             "test"
report STRIPE_PRICE_PRO               "Pro — monthly       (\$79 / mo)"              "test"
report STRIPE_PRICE_PRO_ANNUAL        "Pro — annual        (\$790 / yr)"             "test"
report STRIPE_PRICE_AGENCY            "Agency — per-seat monthly (\$79 / seat)"      "test"
report STRIPE_PRICE_AGENCY_ANNUAL     "Agency — per-seat annual  (\$790 / seat/yr)"  "test"
report STRIPE_PRICE_CREDIT_PACK_SMALL "Credit pack — \$3 one-time (5 scans + 3 takedowns)" "test"
echo ""
hr

# 2) The steps
if [ "$1" != "--check" ]; then
  printf "${CYAN}Step 1: Create products + prices in the Dashboard${NC}\n"
  printf "  1. Go to https://dashboard.stripe.com/products\n"
  printf "  2. Click 'Add product' three times. For each product, add TWO prices:\n\n"
  printf "     ${YELLOW}Product 1: Standard${NC}\n"
  printf "       Price 1:  \$29.00 / month   (recurring)\n"
  printf "       Price 2:  \$290.00 / year    (recurring)  ← 2 months free\n\n"
  printf "     ${YELLOW}Product 2: Pro${NC}\n"
  printf "       Price 1:  \$79.00 / month   (recurring)\n"
  printf "       Price 2:  \$790.00 / year   (recurring)  ← 2 months free\n\n"
  printf "     ${YELLOW}Product 3: Agency (per-seat)${NC}\n"
  printf "       Price 1:  \$79.00 / seat / month   (recurring, tiered)\n"
  printf "       Price 2:  \$790.00 / seat / year   (recurring)\n"
  printf "       (Seats are set by quantity on the subscription, not separate prices.)\n\n"
  printf "     ${YELLOW}Product 4: Credit Pack (one-time)${NC}\n"
  printf "       Price:     \$3.00 ONE-TIME (NOT recurring — this is mode='payment')\n"
  printf "       (This is the small credit pack — 5 scans + 3 takedowns, never expires.)\n\n"
  printf "  3. For each price, copy the 'API id' (price_...)\n"
  printf "  4. While you're there, also copy your:\n"
  printf "       - Secret key       (Developers -> API keys -> Secret key)\n"
  printf "       - Publishable key (Developers -> API keys -> Publishableable key)\n"
  echo ""

  printf "${CYAN}Step 2: Create the webhook endpoint${NC}\n"
  printf "  1. Go to https://dashboard.stripe.com/webhooks\n"
  printf "  2. Click 'Add endpoint'\n"
  printf "       URL:     https://shield.vesamuni.com/webhook/stripe\n"
  printf "       Events:  checkout.session.completed\n"
  printf "                customer.subscription.updated\n"
  printf "                customer.subscription.deleted\n"
  printf "                invoice.payment_failed\n"
  printf "  3. Open the endpoint, click 'Reveal' under Signing secret, copy it (whsec_...)\n"
  echo ""

  printf "${CYAN}Step 3: (optional) Enable Stripe Tax + promo codes${NC}\n"
  printf "  - Tax:   Settings -> Tax -> Enable. The checkout auto-collects\n"
  printf "           based on customer billing address.\n"
  printf "  - Promo: Settings -> Customer portal -> Allow promotion codes\n"
  printf "           (also auto-enabled on checkout, but portal needs it too).\n"
  echo ""

  printf "${CYAN}Step 4: Fill .env and restart${NC}\n"
  printf "  Edit .env and replace the _xxx placeholders with real values:\n"
  cat <<EOF
    STRIPE_SECRET_KEY=sk_test_xxxxxxxxxxxxxxxxxxxxxxxx
    STRIPE_PUBLISHABLE_KEY=pk_test_xxxxxxxxxxxxxxxxxxxxxxxx
    STRIPE_WEBHOOK_SECRET=whsec_xxxxxxxxxxxxxxxxxxxxxxxx
    STRIPE_PRICE_STANDARD=price_xxxxxxxxxxxxxx
    STRIPE_PRICE_STANDARD_ANNUAL=price_xxxxxxxxxxxxxx
    STRIPE_PRICE_PRO=price_xxxxxxxxxxxxxx
    STRIPE_PRICE_PRO_ANNUAL=price_xxxxxxxxxxxxxx
    STRIPE_PRICE_AGENCY=price_xxxxxxxxxxxxxx
    STRIPE_PRICE_AGENCY_ANNUAL=price_xxxxxxxxxxxxxx
    STRIPE_PRICE_CREDIT_PACK_SMALL=price_xxxxxxxxxxxxxx
EOF
  printf "  Then restart:  npm start\n"
  echo ""
fi

# 3) Test mode validator
if [ "$1" = "--test" ] || [ "$1" = "--check" ]; then
  if [ "$GOOD" = "0" ]; then
    printf "${RED}Some env vars are missing. Set them in .env and re-run.${NC}\n"
    exit 1
  fi
  printf "${GREEN}All env vars present.${NC} Running billing test...\n\n"
  node test/run.js billing
fi
