#!/usr/bin/env bash
# Smoke test pagamenti: pagina billing + redirect Checkout (+ opzionale profilo completo).
set -euo pipefail

BASE="${BASE_URL:-https://www.matchlivetv.it}"
EMAIL="${TEST_EMAIL:-coach@matchlivetv.test}"
PASSWORD="${TEST_PASSWORD:-password123}"
PLAN="${TEST_PLAN:-premium_light}"
COOKIES=$(mktemp)
trap 'rm -f "$COOKIES"' EXIT

pass=0
fail=0
ok() { echo "OK  $1"; pass=$((pass+1)); }
ko() { echo "FAIL $1"; fail=$((fail+1)); }

echo "== Stripe E2E smoke @ $BASE =="

curl -sf "$BASE/up" >/dev/null && ok "health /up" || ko "health /up"

curl -sf -c "$COOKIES" "$BASE/login" -o /tmp/mltv_login.html
T=$(grep -oP 'name="authenticity_token" value="\K[^"]+' /tmp/mltv_login.html | head -1 || true)
if [[ -z "$T" ]]; then
  ko "login page (token CSRF)"
else
  CODE=$(curl -s -o /dev/null -w "%{http_code}" -c "$COOKIES" -b "$COOKIES" -X POST "$BASE/login" \
    -d "authenticity_token=$T" -d "email=$EMAIL" -d "password=$PASSWORD")
  [[ "$CODE" == "302" || "$CODE" == "303" ]] && ok "login $EMAIL" || ko "login ($CODE)"
fi

CLUB_LINK=$(curl -sf -b "$COOKIES" "$BASE/" | grep -oP 'href="/clubs/[^"]+/billing"' | head -1 || true)
if [[ -z "$CLUB_LINK" ]]; then
  # prova da pagina clubs
  CLUB_ID=$(curl -sf -b "$COOKIES" "$BASE/" | grep -oP '/clubs/[0-9a-f-]{36}' | head -1 | sed 's|/clubs/||' || true)
  CLUB_LINK="/clubs/${CLUB_ID}/billing"
fi

if [[ -z "${CLUB_LINK:-}" || "$CLUB_LINK" == "/clubs//billing" ]]; then
  ko "trova link billing club"
else
  ok "billing path $CLUB_LINK"
  BODY=$(curl -sf -b "$COOKIES" "$BASE$CLUB_LINK")
  echo "$BODY" | grep -qi "stripe non configurato" && ko "Stripe abilitato in UI" || ok "Stripe abilitato in UI"
  echo "$BODY" | grep -q "Attiva Premium" && ok "pulsante Attiva Premium" || ko "pulsante Attiva Premium"
  echo "$BODY" | grep -q "Dati di fatturazione" && ok "link profilo fatturazione" || ko "link profilo fatturazione"

  CHECKOUT_URL="${CLUB_LINK%/billing}/checkout?plan=${PLAN}"
  HEADERS=$(curl -s -D - -o /dev/null -b "$COOKIES" "$BASE$CHECKOUT_URL" | tr -d '\r')
  if echo "$HEADERS" | grep -qi "location:.*checkout\.stripe\.com"; then
    ok "redirect Stripe Checkout"
  elif echo "$HEADERS" | grep -qi "location:.*billing/profile"; then
    ok "redirect profilo fatturazione (dati incompleti — completa prima del pagamento)"
  else
    ko "redirect checkout (atteso checkout.stripe.com o billing/profile)"
    echo "$HEADERS" | grep -i "^location:" | head -3 || true
  fi
fi

echo ""
echo "Risultato: $pass OK, $fail FAIL"
[[ "$fail" -eq 0 ]]
