#!/bin/bash
# simulate-purchases.sh — Simula N compras reales del marketplace BewPro
#
# Para cada producto/core en la lista:
#   1. Crea Customer real en Stripe (test mode)
#   2. Crea Subscription real con trial 15 días + metadata
#   3. Construye checkout.session.completed event con los IDs reales
#   4. POST al webhook de bewpro22 con HMAC SHA256 signature válida
#
# Resultado: el flujo completo se ejecuta como compra real:
# - Webhook handler crea Project en Airtable + Subscription tracking
# - Email "pedido recibido" desde hola@bewpro.com
# - Cron process-airtable.sh detecta y provisiona
# - DNS + cPanel + SSL + bewpro:new
# - Email credenciales desde noreply@bewpro.com
#
# Uso:
#   ./simulate-purchases.sh <email> [--dry-run]
#
# Requiere variables en /Applications/XAMPP/xamppfiles/htdocs/cd-system/.env:
#   STRIPE_SECRET, STRIPE_WEBHOOK_SECRET

set -uo pipefail

REPO_ROOT="/Applications/XAMPP/xamppfiles/htdocs/cd-system"
WEBHOOK_URL="https://bewpro.com/stripe/webhook"
DRY_RUN=false
EMAIL="${1:-}"

if [[ "$EMAIL" == "--dry-run" || -z "$EMAIL" ]]; then
  echo "Uso: $0 <email> [--dry-run]" >&2
  exit 1
fi

[[ "${2:-}" == "--dry-run" ]] && DRY_RUN=true

set -a && source "$REPO_ROOT/.env" && set +a

if [[ -z "${STRIPE_SECRET:-}" || -z "${STRIPE_WEBHOOK_SECRET:-}" ]]; then
  echo "ERROR: STRIPE_SECRET y STRIPE_WEBHOOK_SECRET deben estar en .env" >&2
  exit 1
fi

########################################
# 9 CORES PUBLICADOS (2 compras cada uno = 18 totales)
# Formato: slug | name | price_id | titulo_proyecto_1 | titulo_proyecto_2
########################################

PRODUCTS=(
  "foundations-ong|Foundation/NGO|price_1TS47eLFhmxhEqlTt1ot7atM|Demo Fundacion Esperanza|Demo ONG Solidaria"
  "creative-video-editor|Portfolio para Editor de Video|price_1TS3qkLFhmxhEqlT4zqsft7k|Demo Editor Pro|Demo Cinegrafia Studio"
  "corporative|Sitio Web Corporativo|price_1T9RicLFhmxhEqlTa0MJns7i|Demo Corp Alpha|Demo Corp Beta"
  "construction|Sitio Web para Constructoras|price_1T9RidLFhmxhEqlTRyDuZqk9|Demo Construct Sur|Demo Obras Norte"
  "art-design|Sitio Web para Creativos y Disenadores|price_1T9RidLFhmxhEqlTRyDuZqk9|Demo Estudio Creativo|Demo Diseno Studio"
  "law-firm-digital|Sitio Web para Estudios Juridicos|price_1T9RidLFhmxhEqlTRyDuZqk9|Demo Abogados SRL|Demo Legal Asesores"
  "real-estate|Sitio Web para Inmobiliarias|price_1T9RieLFhmxhEqlTaW6S46Jn|Demo Inmo Premium|Demo Propiedades Sur"
  "restaurant-bar|Sitio Web para Restaurantes y Bares|price_1T9RicLFhmxhEqlTa0MJns7i|Demo Bistro Central|Demo Cafe Central"
  "personal-brand|Sitio Web Personal y Portfolio|price_1T9RicLFhmxhEqlTa0MJns7i|Demo Personal Brand 1|Demo Personal Brand 2"
)

# IMPORTANTE: NO usar nombres que empiecen con "test" — cPanel/WHM rechaza
# usernames reservados (XID g2deht: "testX is a reserved username on this system").
# Usar "Demo" o cualquier prefijo no-reservado.

########################################
# FUNCIÓN: Crear Customer + Subscription en Stripe (real, test mode)
########################################
create_stripe_subscription() {
  local price_id="$1" project_title="$2" product_slug="$3" product_name="$4"

  # 1. Customer
  local customer_resp
  customer_resp=$(curl -s -u "${STRIPE_SECRET}:" https://api.stripe.com/v1/customers \
    -d "email=${EMAIL}" \
    -d "name=Test Buyer ${project_title}" \
    -d "metadata[test_simulation]=true")
  local customer_id
  customer_id=$(echo "$customer_resp" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)
  if [[ -z "$customer_id" ]]; then
    echo "  ERROR creando customer: $customer_resp" >&2
    return 1
  fi

  # 2. Subscription con trial 15d (no requiere payment method para que arranque)
  local sub_resp
  sub_resp=$(curl -s -u "${STRIPE_SECRET}:" https://api.stripe.com/v1/subscriptions \
    -d "customer=${customer_id}" \
    -d "items[0][price]=${price_id}" \
    -d "trial_period_days=15" \
    -d "trial_settings[end_behavior][missing_payment_method]=cancel" \
    -d "metadata[product_slug]=${product_slug}" \
    -d "metadata[product_name]=${product_name}" \
    -d "metadata[user_email]=${EMAIL}" \
    -d "metadata[user_name]=Test Buyer" \
    -d "metadata[test_simulation]=true")
  local sub_id sub_status
  sub_id=$(echo "$sub_resp" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)
  sub_status=$(echo "$sub_resp" | python3 -c "import sys,json; print(json.load(sys.stdin).get('status',''))" 2>/dev/null)
  if [[ -z "$sub_id" ]]; then
    echo "  ERROR creando subscription: $sub_resp" >&2
    return 1
  fi

  echo "${customer_id}|${sub_id}|${sub_status}"
}

########################################
# FUNCIÓN: Build + sign + POST checkout.session.completed event
########################################
send_webhook_event() {
  local customer_id="$1" sub_id="$2" project_title="$3" product_slug="$4" product_name="$5" price_cents="$6"

  local session_id="cs_test_simulated_$(date +%s%N | tail -c 12)$(( RANDOM ))"
  local event_id="evt_test_simulated_$(date +%s%N | tail -c 12)$(( RANDOM ))"
  local timestamp=$(date +%s)

  # JSON del evento — formato Stripe oficial checkout.session.completed
  local body
  body=$(python3 -c "
import json, sys
event = {
    'id': sys.argv[1],
    'object': 'event',
    'type': 'checkout.session.completed',
    'created': int(sys.argv[2]),
    'livemode': False,
    'data': {
        'object': {
            'id': sys.argv[3],
            'object': 'checkout.session',
            'customer': sys.argv[4],
            'subscription': sys.argv[5],
            'amount_total': int(sys.argv[6]),
            'currency': 'usd',
            'mode': 'subscription',
            'status': 'complete',
            'payment_status': 'paid',
            'customer_details': {
                'email': sys.argv[7],
                'name': 'Test Buyer',
                'address': {'country': 'AR'}
            },
            'metadata': {
                'product_slug': sys.argv[8],
                'product_name': sys.argv[9],
                'user_email': sys.argv[7],
                'user_name': 'Test Buyer',
                'test_simulation': 'true',
            },
            'custom_fields': [
                {
                    'key': 'project_title',
                    'label': {'type': 'custom', 'custom': 'Nombre del proyecto'},
                    'type': 'text',
                    'text': {'value': sys.argv[10]}
                }
            ]
        }
    }
}
print(json.dumps(event, separators=(',', ':')))
" "$event_id" "$timestamp" "$session_id" "$customer_id" "$sub_id" "$price_cents" "$EMAIL" "$product_slug" "$product_name" "$project_title")

  # Calcular HMAC SHA256 signature
  local signed_payload="${timestamp}.${body}"
  local signature
  signature=$(printf '%s' "$signed_payload" | openssl dgst -sha256 -hmac "$STRIPE_WEBHOOK_SECRET" -binary | xxd -p -c 256)

  local sig_header="t=${timestamp},v1=${signature}"

  # POST al webhook
  local http_code
  http_code=$(curl -s -X POST "$WEBHOOK_URL" \
    -H "Content-Type: application/json" \
    -H "Stripe-Signature: ${sig_header}" \
    -H "User-Agent: Stripe-Simulated/1.0" \
    -d "$body" \
    -o /tmp/sim-webhook-resp.txt \
    -w "%{http_code}")

  echo "${http_code}|${session_id}"
}

########################################
# MAIN
########################################

echo "=================================================="
echo "  SIMULATE PURCHASES — BewPro Marketplace"
echo "  Email: $EMAIL"
echo "  Total: $((${#PRODUCTS[@]} * 2)) compras (2 x ${#PRODUCTS[@]} cores)"
[[ "$DRY_RUN" == "true" ]] && echo "  MODE: DRY RUN"
echo "=================================================="
echo ""

TOTAL=0
SUCCESS=0
FAILED=0

for product_line in "${PRODUCTS[@]}"; do
  IFS='|' read -r slug name price_id title1 title2 <<< "$product_line"

  # 2 compras por producto (con 2 títulos distintos)
  for title in "$title1" "$title2"; do
    TOTAL=$((TOTAL + 1))
    echo "[$TOTAL/18] $slug — \"$title\""

    if [[ "$DRY_RUN" == "true" ]]; then
      echo "  [DRY] Crearía Stripe sub para $price_id + webhook event"
      SUCCESS=$((SUCCESS + 1))
      continue
    fi

    # 1) Crear sub real en Stripe
    stripe_result=$(create_stripe_subscription "$price_id" "$title" "$slug" "$name")
    if [[ -z "$stripe_result" ]]; then
      echo "  ❌ Stripe creation falló"
      FAILED=$((FAILED + 1))
      continue
    fi
    customer_id=$(echo "$stripe_result" | cut -d'|' -f1)
    sub_id=$(echo "$stripe_result" | cut -d'|' -f2)
    sub_status=$(echo "$stripe_result" | cut -d'|' -f3)
    echo "  Stripe: customer=$customer_id sub=$sub_id status=$sub_status"

    # 2) Sleep para asegurar que la sub se materializó en Stripe
    sleep 2

    # 3) Get amount from price
    price_resp=$(curl -s -u "${STRIPE_SECRET}:" "https://api.stripe.com/v1/prices/${price_id}")
    price_cents=$(echo "$price_resp" | python3 -c "import sys,json; print(json.load(sys.stdin).get('unit_amount',0))" 2>/dev/null)

    # 4) Send webhook event
    webhook_result=$(send_webhook_event "$customer_id" "$sub_id" "$title" "$slug" "$name" "$price_cents")
    http_code=$(echo "$webhook_result" | cut -d'|' -f1)
    session_id=$(echo "$webhook_result" | cut -d'|' -f2)

    if [[ "$http_code" =~ ^2 ]]; then
      echo "  ✅ Webhook: HTTP $http_code (session=$session_id)"
      SUCCESS=$((SUCCESS + 1))
    else
      echo "  ❌ Webhook: HTTP $http_code"
      cat /tmp/sim-webhook-resp.txt | head -3
      FAILED=$((FAILED + 1))
    fi

    # Sleep entre compras para no saturar webhook
    sleep 3
  done
done

echo ""
echo "=================================================="
echo "  Resultado: $SUCCESS OK, $FAILED fallidos (de $TOTAL)"
echo "=================================================="
echo ""
echo "Próximo paso: el cron process-airtable.sh va a procesar"
echo "los Project records (Pipeline_Status=Required) en orden,"
echo "uno por minuto. Provisión completa: ~$((TOTAL * 3 / 2)) minutos"
echo "(con load balancing dual-VPS)."
echo ""
echo "Monitoreo:"
echo "  ssh vps1-claude 'tail -f /var/log/process-airtable.log'"
echo "  Airtable: https://airtable.com/appRxvpzqCmNsw2JN"
