#!/usr/bin/env bash
# Test scelta mensile/annuale + redirect Checkout con price id corretto
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
COMPOSE="docker compose -f $ROOT/infra/docker-compose.yml"
BASE="${BASE_URL:-http://localhost:3000}"
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)); }

read_env() {
  grep -E "^$1=" "$ROOT/infra/.env" 2>/dev/null | head -1 | cut -d= -f2- | tr -d '\r' || true
}

YEARLY_LIGHT=$(read_env STRIPE_PREMIUM_LIGHT_YEARLY_PRICE_ID)
[[ -z "$YEARLY_LIGHT" ]] && YEARLY_LIGHT=$(read_env STRIPE_PREMIUM_LIGHT_PRICE_ID)
MONTHLY_LIGHT=$(read_env STRIPE_PREMIUM_LIGHT_MONTHLY_PRICE_ID)

login() {
  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)
  curl -sf -c "$COOKIES" -b "$COOKIES" -X POST "$BASE/login" \
    -d "authenticity_token=$T" -d "email=coach@matchlivetv.test" -d "password=password123" -o /dev/null
}

echo "== Test intervalli billing =="

$COMPOSE exec -T rails bundle exec rails db:migrate >/dev/null 2>&1 || true

$COMPOSE exec -T rails bundle exec rails runner "
club = Club.first
club.update!(
  billing_legal_name: 'ASD Test', billing_email: 'bill@test.it',
  billing_address_line: 'Via 1', billing_city: 'Milano', billing_postal_code: '20100',
  billing_vat_number: '12345678901', billing_recipient_code: 'ABCDEFG'
)
sub = club.subscription || club.create_subscription!(plan: Plan['free'], status: 'active')
sub.update!(plan: Plan['free'], stripe_subscription_id: nil, billing_interval: nil)
puts club.id
" >/dev/null 2>&1 && ok "setup club billing" || ko "setup club billing"

CLUB_ID=$($COMPOSE exec -T rails bundle exec rails runner "puts Club.first.id" 2>/dev/null | tail -1)

login && ok "login" || ko "login"

BODY=$(curl -sf -b "$COOKIES" "$BASE/clubs/$CLUB_ID/billing")
echo "$BODY" | grep -q "Attiva Premium Light — €40/anno" && ok "UI bottone annuale Light" || ko "UI bottone annuale Light"
if [[ -n "$MONTHLY_LIGHT" ]]; then
  echo "$BODY" | grep -q "Attiva Premium Light — €5/mese" && ok "UI bottone mensile Light" || ko "UI bottone mensile Light"
else
  echo "$BODY" | grep -q "€5/mese" && ko "UI mensile assente se non configurato" || ok "UI mensile nascosto (price id mancante)"
fi

if [[ -n "$YEARLY_LIGHT" ]]; then
  HEADERS=$(curl -s -D - -o /dev/null -b "$COOKIES" "$BASE/clubs/$CLUB_ID/checkout?plan=premium_light&interval=yearly" | tr -d '\r')
  if echo "$HEADERS" | grep -qi "location:.*checkout\.stripe\.com"; then
    ok "redirect checkout annuale"
  else
    ko "redirect checkout annuale"
  fi

  PRICE_USED=$($COMPOSE exec -T rails bundle exec rails runner "
    puts Billing::Stripe::PriceCatalog.price_id(plan_slug: 'premium_light', interval: 'yearly')
  " 2>/dev/null | tail -1)
  [[ "$PRICE_USED" == "$YEARLY_LIGHT" ]] && ok "price id annuale corretto ($PRICE_USED)" || ko "price id annuale ($PRICE_USED vs $YEARLY_LIGHT)"
fi

$COMPOSE exec -T rails bundle exec rspec \
  spec/services/billing/stripe/price_catalog_spec.rb \
  spec/services/billing/stripe/checkout_session_spec.rb \
  spec/services/billing/stripe/change_plan_spec.rb \
  spec/helpers/public/billing_helper_spec.rb \
  --format progress 2>&1 | tail -3
RS=$?
[[ $RS -eq 0 ]] && ok "RSpec billing intervals" || ko "RSpec billing intervals"

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