#!/usr/bin/env bash
# E2E: FOSSBilling → bridge :18087 → opencli user-add + domains-add
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}"
BRIDGE_URL="${BRIDGE_URL:-http://127.0.0.1:18087}"
TEST_USER="test$(date +%s | tail -c 6)"
TEST_EMAIL="${TEST_USER}@testprovision.ligbox.com.br"
TEST_PASS="LbTest805353"
TEST_DOMAIN="${TEST_USER}.ligbox.com.br"
COOKIE_JAR="$(mktemp)"
trap 'rm -f "$COOKIE_JAR"' EXIT

resolve_op_user() {
  opencli user-list 2>/dev/null | awk -F'|' -v em="$1" '
    NR>3 && $0 !~ /^\+/ {
      gsub(/^ *| *$/,"",$3); gsub(/^ *| *$/,"",$4);
      if ($4==em) { print $3; exit }
    }'
}

user_exists_in_list() {
  opencli user-list 2>/dev/null | awk -F'|' -v u="$1" '
    NR>3 && $0 !~ /^\+/ { gsub(/^ *| *$/,"",$3); if ($3==u) { found=1; exit } }
    END { exit !found }'
}

echo "=== E2E FOSS → Bridge → OpenPanel (conta + domínio) ==="
echo "User: ${TEST_USER} | Domain: ${TEST_DOMAIN}"

echo "[1/7] 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 "FALHOU login: $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/7] Criar cliente FOSS..."
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=E2E&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 "FALHOU cliente: $CLIENT"; exit 1; }
echo "    client_id=${CID}"

echo "[3/7] Criar + activar encomenda hosting (product_id=2)..."
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" \
  -d "config[domain][action]=owndomain" \
  -d "config[domain][owndomain_sld]=${TEST_USER}" \
  -d "config[domain][owndomain_tld]=ligbox.com.br")
echo "$ORDER" | python3 -m json.tool 2>/dev/null | head -15 || 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 [[ -n "$OID" ]]; then
  echo "    order_id=${OID} — aguardar provisionamento (até 120s)..."
  curl -sk -b "$COOKIE_JAR" -X POST "${FOSS_URL}/api/admin/order/activate" \
    -d "CSRFToken=${CSRF}&id=${OID}" >/dev/null 2>&1 || true
  for i in $(seq 1 24); do
    OP_USER=$(resolve_op_user "${TEST_EMAIL}")
    [[ -n "$OP_USER" ]] && break
    sleep 5
  done
else
  echo "    Order API sem ID — fallback bridge directo..."
  TOKEN=$(curl -sf --max-time 30 -X POST "${BRIDGE_URL}/api" -H "Content-Type: application/json" \
    -d '{"username":"ligboxadmin","password":"LbOpen805353"}' | python3 -c "import sys,json; print(json.load(sys.stdin)['access_token'])")
  curl -sf --max-time 180 -X POST "${BRIDGE_URL}/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\",\"domain\":\"${TEST_DOMAIN}\"}" \
    | python3 -m json.tool
fi

echo "[4/7] Resolver username OpenPanel (FOSS gera username próprio)..."
for _ in $(seq 1 12); do
  [[ -n "${OP_USER:-}" ]] || OP_USER=$(resolve_op_user "${TEST_EMAIL}")
  [[ -n "${OP_USER:-}" ]] && break
  sleep 5
done
[[ -n "$OP_USER" ]] || { echo "FALHOU — user não encontrado por email ${TEST_EMAIL}"; opencli user-list 2>/dev/null; exit 1; }
echo "    openpanel_user=${OP_USER}"

echo "[5/7] Verificar conta hosting..."
user_exists_in_list "${OP_USER}" || { echo "FALHOU — user ${OP_USER} não existe"; exit 1; }
echo "    OK user ${OP_USER}"

echo "[6/7] Verificar domínio ${TEST_DOMAIN}..."
DOMAINS=$(opencli domains-user "${OP_USER}" 2>/dev/null || true)
if echo "$DOMAINS" | grep -qF "${TEST_DOMAIN}"; then
  echo "    OK domínio ${TEST_DOMAIN} associado"
else
  echo "    Domínio em falta ou mal formatado — corrigir..."
  # remover domínio errado (sem ponto) se existir
  BAD_DOMAIN="${TEST_USER}ligbox.com.br"
  opencli domains-user "${OP_USER}" 2>/dev/null | grep -qF "${BAD_DOMAIN}" && \
    opencli domains-delete "${BAD_DOMAIN}" "${OP_USER}" -y 2>/dev/null || true
  opencli domains-add "${TEST_DOMAIN}" "${OP_USER}" 2>&1 | tail -3
  DOMAINS=$(opencli domains-user "${OP_USER}" 2>/dev/null || true)
  echo "$DOMAINS"
  echo "$DOMAINS" | grep -qF "${TEST_DOMAIN}" || { echo "FALHOU domínio"; exit 1; }
fi

echo "[7/7] Teste email CLI desbloqueado..."
if opencli email-setup 2>&1 | grep -qi "Community edition does not support"; then
  echo "    AVISO email ainda bloqueado — reaplicar patch-openpanel-ce-unlock.sh"
else
  echo "    OK email CLI acessível"
fi

echo ""
echo "=== E2E SUCESSO ==="
echo "  OpenPanel: https://openpanel.ligbox.com.br"
echo "  User:      ${OP_USER}"
echo "  Pass:      ${TEST_PASS}"
echo "  Domain:    ${TEST_DOMAIN}"
echo ""
echo "Limpeza (opcional): opencli user-delete ${OP_USER} -y"
