#!/usr/bin/env bash
# Configura Stripe sul server di produzione e verifica l'integrazione.
#
# Uso:
#   ./scripts/setup_stripe_production.sh                    # legge infra/.env locale
#   ./scripts/setup_stripe_production.sh --webhook-secret whsec_xxx
#   STRIPE_MODE=live ./scripts/setup_stripe_production.sh   # usa chiavi live nel .env
#
# Prima di eseguire in LIVE:
#   1. Stripe Dashboard → modalità Live → crea prodotti/prezzi → copia price_...
#   2. Webhook endpoint: https://www.matchlivetv.it/webhooks/stripe
#      Eventi: checkout.session.completed, customer.subscription.*, invoice.paid, invoice.payment_failed
#   3. Incolla whsec_... live in infra/.env come STRIPE_WEBHOOK_SECRET
#
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
ENV_FILE="${ENV_FILE:-$ROOT/infra/.env}"
SERVER="${DEPLOY_SERVER:-eminux@192.168.1.146}"
REMOTE_DIR="${DEPLOY_PATH:-/opt/matchlivetv}"
WEBHOOK_SECRET=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --env-file) ENV_FILE="$2"; shift 2 ;;
    --webhook-secret) WEBHOOK_SECRET="$2"; shift 2 ;;
    -h|--help)
      sed -n '2,14p' "$0"
      exit 0
      ;;
    *) echo "Argomento sconosciuto: $1" >&2; exit 1 ;;
  esac
done

if [[ ! -f "$ENV_FILE" ]]; then
  echo "File non trovato: $ENV_FILE" >&2
  exit 1
fi

read_env() {
  local key="$1"
  grep -E "^${key}=" "$ENV_FILE" | head -1 | cut -d= -f2- | tr -d '\r'
}

STRIPE_SECRET_KEY="$(read_env STRIPE_SECRET_KEY)"
STRIPE_PREMIUM_LIGHT_PRICE_ID="$(read_env STRIPE_PREMIUM_LIGHT_PRICE_ID)"
STRIPE_PREMIUM_FULL_PRICE_ID="$(read_env STRIPE_PREMIUM_FULL_PRICE_ID)"
[[ -z "$WEBHOOK_SECRET" ]] && WEBHOOK_SECRET="$(read_env STRIPE_WEBHOOK_SECRET)"

STRIPE_PREMIUM_LIGHT_YEARLY_PRICE_ID="${STRIPE_PREMIUM_LIGHT_YEARLY_PRICE_ID:-$(read_env STRIPE_PREMIUM_LIGHT_PRICE_ID)}"
STRIPE_PREMIUM_FULL_YEARLY_PRICE_ID="${STRIPE_PREMIUM_FULL_YEARLY_PRICE_ID:-$(read_env STRIPE_PREMIUM_FULL_PRICE_ID)}"
STRIPE_PREMIUM_LIGHT_MONTHLY_PRICE_ID="${STRIPE_PREMIUM_LIGHT_MONTHLY_PRICE_ID:-}"
STRIPE_PREMIUM_FULL_MONTHLY_PRICE_ID="${STRIPE_PREMIUM_FULL_MONTHLY_PRICE_ID:-}"

for var in STRIPE_SECRET_KEY STRIPE_PREMIUM_LIGHT_YEARLY_PRICE_ID STRIPE_PREMIUM_FULL_YEARLY_PRICE_ID; do
  if [[ -z "${!var:-}" ]]; then
    echo "Manca $var in $ENV_FILE" >&2
    exit 1
  fi
done

if [[ -z "$WEBHOOK_SECRET" ]]; then
  echo "Manca STRIPE_WEBHOOK_SECRET." >&2
  echo "Crea un endpoint in Stripe → https://www.matchlivetv.it/webhooks/stripe" >&2
  echo "Poi: $0 --webhook-secret whsec_..." >&2
  exit 1
fi

if [[ "${STRIPE_SECRET_KEY}" == sk_test_* ]]; then
  echo "Modalità: TEST (sk_test_) — pagamenti solo con carte di prova Stripe."
elif [[ "${STRIPE_SECRET_KEY}" == sk_live_* ]]; then
  echo "Modalità: LIVE (sk_live_) — pagamenti reali."
else
  echo "ATTENZIONE: STRIPE_SECRET_KEY non sembra sk_test_ né sk_live_" >&2
fi

echo "Aggiorno $SERVER:$REMOTE_DIR/infra/.env ..."

ssh "$SERVER" "bash -s" <<REMOTE
set -euo pipefail
ENV="$REMOTE_DIR/infra/.env"
touch "\$ENV"
upsert() {
  local key="\$1" val="\$2"
  if grep -q "^\${key}=" "\$ENV" 2>/dev/null; then
    sed -i "s|^\${key}=.*|\${key}=\${val}|" "\$ENV"
  else
    echo "\${key}=\${val}" >> "\$ENV"
  fi
}
upsert STRIPE_SECRET_KEY '${STRIPE_SECRET_KEY}'
upsert STRIPE_WEBHOOK_SECRET '${WEBHOOK_SECRET}'
upsert STRIPE_PREMIUM_LIGHT_MONTHLY_PRICE_ID '${STRIPE_PREMIUM_LIGHT_MONTHLY_PRICE_ID}'
upsert STRIPE_PREMIUM_LIGHT_YEARLY_PRICE_ID '${STRIPE_PREMIUM_LIGHT_YEARLY_PRICE_ID}'
upsert STRIPE_PREMIUM_FULL_MONTHLY_PRICE_ID '${STRIPE_PREMIUM_FULL_MONTHLY_PRICE_ID}'
upsert STRIPE_PREMIUM_FULL_YEARLY_PRICE_ID '${STRIPE_PREMIUM_FULL_YEARLY_PRICE_ID}'
upsert STRIPE_PREMIUM_LIGHT_PRICE_ID '${STRIPE_PREMIUM_LIGHT_YEARLY_PRICE_ID}'
upsert STRIPE_PREMIUM_FULL_PRICE_ID '${STRIPE_PREMIUM_FULL_YEARLY_PRICE_ID}'
REMOTE

echo "Sync codice..."
bash "$ROOT/scripts/deploy/sync_to_server.sh"

echo "Rebuild rails + seed piani..."
ssh "$SERVER" "cd $REMOTE_DIR/infra && docker compose -f docker-compose.prod.yml --env-file .env up -d --build rails"
sleep 20
ssh "$SERVER" "cd $REMOTE_DIR/infra && docker compose -f docker-compose.prod.yml exec -T rails bundle exec rails db:seed" || true

echo "Verifica..."
ssh "$SERVER" "cd $REMOTE_DIR/infra && docker compose -f docker-compose.prod.yml exec -T rails bundle exec rails runner \"
  puts 'stripe_enabled=' + MatchLiveTv.stripe_enabled?.to_s
  puts 'light_price=' + (Plan['premium_light'].stripe_price_id || 'MISSING').to_s
  puts 'full_price=' + (Plan['premium_full'].stripe_price_id || 'MISSING').to_s
\""

echo ""
echo "Prossimo passo: test browser"
echo "  1. Login su https://www.matchlivetv.it/login"
echo "  2. Società → Abbonamento → Attiva Premium Light"
echo "  3. Carta test 4242 4242 4242 4242 (solo se sk_test_)"
echo "  4. Stripe Dashboard → Webhooks → verifica eventi 200 su /webhooks/stripe"
