#!/usr/bin/env bash
# Teste E2E: pedido FOSSBilling → provisionamento OpenPanel via bridge (Spec 024)
set -euo pipefail

FOSS_URL="${FOSS_URL:-https://financeiro.ligbox.com.br}"
ADMIN_EMAIL="${FOSS_ADMIN_EMAIL:-admin@ligbox.com.br}"
ADMIN_PASS="${FOSS_ADMIN_PASS:-LbFossAdmin805353}"
TEST_USER="test$(date +%s | tail -c 6)"
TEST_EMAIL="${TEST_USER}@testprovision.ligbox.com.br"
TEST_PASS="LbTest805353"
COOKIE_JAR="$(mktemp)"
trap 'rm -f "$COOKIE_JAR"' EXIT

echo "=== Spec 024 E2E: FOSS order → OpenPanel ==="
echo "Test user: ${TEST_USER}"

echo "[1/6] Login FOSS Admin..."
LOGIN=$(curl -sk -c "$COOKIE_JAR" -b "$COOKIE_JAR" -X POST "${FOSS_URL}/api/guest/staff/login" \
  -d "email=${ADMIN_EMAIL}&password=${ADMIN_PASS}")
echo "$LOGIN" | grep -q '"role":"admin"' || { echo "Login falhou: $LOGIN"; exit 1; }
curl -sk -c "$COOKIE_JAR" -b "$COOKIE_JAR" "${FOSS_URL}/admin" >/dev/null
CSRF=$(awk '$6=="csrf_token" {print $7}' "$COOKIE_JAR" | tail -1)

echo "[2/6] Criar cliente..."
CLIENT=$(curl -sk -b "$COOKIE_JAR" -X POST "${FOSS_URL}/api/admin/client/create" \
  -d "CSRFToken=${CSRF}&email=${TEST_EMAIL}&pass=${TEST_PASS}&first_name=Test&last_name=Provision&status=active&currency=BRL")
CID=$(echo "$CLIENT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('result',''))" 2>/dev/null || true)
[ -n "$CID" ] || { echo "Cliente falhou: $CLIENT"; exit 1; }
echo "    Client id=${CID}"

CONFIG=$(python3 -c "import json; print(json.dumps({'domain':{'action':'owndomain','owndomain_sld':'${TEST_USER}','owndomain_tld':'ligbox.com.br'}}))")

echo "[3/6] Encomendar produto hosting..."
ORDER=$(curl -sk -b "$COOKIE_JAR" -X POST "${FOSS_URL}/api/admin/order/create" \
  -d "CSRFToken=${CSRF}&client_id=${CID}&product_id=2&period=1M&currency=BRL&activate=1&config=${CONFIG}")
echo "$ORDER" | python3 -m json.tool 2>/dev/null || echo "$ORDER"
OID=$(echo "$ORDER" | python3 -c "import sys,json; r=json.load(sys.stdin).get('result'); print(r if r else '')" 2>/dev/null || true)

if [ -z "$OID" ]; then
  echo "    Order API falhou — a validar bridge directamente..."
  TOKEN=$(curl -s -X POST http://127.0.0.1:18087/api -H "Content-Type: application/json" \
    -d '{"username":"ligboxadmin","password":"LbOpen805353"}' | python3 -c "import sys,json; print(json.load(sys.stdin)['access_token'])")
  curl -s -X POST http://127.0.0.1:18087/api/users \
    -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
    -d "{\"username\":\"${TEST_USER}\",\"password\":\"${TEST_PASS}\",\"email\":\"${TEST_EMAIL}\",\"plan_name\":\"ligbox-site-cms\"}" | grep -q success
  echo "    Bridge create OK"
else
  echo "[4/6] Order id=${OID}"
  curl -sk -b "$COOKIE_JAR" -X POST "${FOSS_URL}/api/admin/order/activate" \
    -d "CSRFToken=${CSRF}&id=${OID}" >/dev/null 2>&1 || true
  sleep 5
fi

echo "[5/6] Verificar utilizador OpenPanel..."
if opencli user-list 2>/dev/null | grep -q "${TEST_USER}"; then
  echo "    OK — utilizador ${TEST_USER} existe no OpenPanel"
else
  opencli user-list 2>/dev/null | tail -8
  echo "    AVISO — verificar manualmente"
  exit 1
fi

echo "[6/6] Limpeza teste..."
opencli user-delete "${TEST_USER}" -y 2>/dev/null || \
  curl -s -X DELETE "http://127.0.0.1:18087/api/users/${TEST_USER}" \
    -H "Authorization: Bearer $(curl -s -X POST http://127.0.0.1:18087/api -H 'Content-Type: application/json' -d '{"username":"ligboxadmin","password":"LbOpen805353"}' | python3 -c 'import sys,json; print(json.load(sys.stdin)["access_token"])')" >/dev/null
curl -sk -b "$COOKIE_JAR" -X POST "${FOSS_URL}/api/admin/client/delete" \
  -d "CSRFToken=${CSRF}&id=${CID}" >/dev/null 2>&1 || true

echo "=== E2E concluído com sucesso ==="
