#!/usr/bin/env bash
# Spec 028 — Teste de confirmação OpenPanel API multidomínio (Ligbox Re-engenharia)
# Uso repetível: bash scripts/test-openpanel-multidomain-api.sh
set -euo pipefail

API_URL="${API_URL:-http://10.10.10.122:8080}"
DESK_USER="${DESK_USER:-root}"
DESK_PASS="${DESK_PASS:-}"
BRIDGE_URL="${BRIDGE_URL:-http://10.10.10.123:18087}"
BRIDGE_TOKEN="${BRIDGE_TOKEN:-ligbox-community-bridge-token}"
MODE="${MODE:-desk}"   # desk | bridge

log() { echo "[$(date -Iseconds)] $*"; }
fail() { log "FAIL: $*"; exit 1; }
ok() { log "OK: $*"; }

if [[ "$MODE" == "desk" ]]; then
  [[ -n "$DESK_PASS" ]] || fail "defina DESK_PASS (senha Desk do utilizador $DESK_USER)"
  log "=== Teste via Desk API ($API_URL) ==="
  TOKEN=$(curl -sf -X POST "$API_URL/api/v1/auth/login" \
    -H "Content-Type: application/json" \
    -d "{\"username\":\"$DESK_USER\",\"password\":\"$DESK_PASS\"}" \
    | python3 -c "import sys,json; print(json.load(sys.stdin)['access_token'])") \
    || fail "login Desk falhou"
  ok "login $DESK_USER"
  RESULT=$(curl -sf --max-time 300 -X POST "$API_URL/api/v1/vm123/openpanel/test-confirm" \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json")
else
  log "=== Teste directo bridge ($BRIDGE_URL) ==="
  SUFFIX=$(date +%s | tail -c 6)
  USER1="apitest${SUFFIX}"
  USER2="apitestb${SUFFIX}"
  D1="apitest${SUFFIX}.ligbox.com.br"
  D2="apitestb${SUFFIX}.ligbox.com.br"
  PASS="LbOpenTest805353"
  HDR=(-H "Authorization: Bearer $BRIDGE_TOKEN" -H "Content-Type: application/json")

  curl -sf "${HDR[@]}" "$BRIDGE_URL/api" | grep -q bridge || fail "bridge health"
  ok "bridge health"

  for pair in "$USER1:$D1" "$USER2:$D2"; do
    U="${pair%%:*}"
    D="${pair##*:}"
    curl -sf --max-time 180 -X POST "${HDR[@]}" -d "{\"username\":\"$U\",\"password\":\"$PASS\",\"email\":\"hosting@$D\",\"domain\":\"$D\",\"plan_name\":\"ligbox-site-cms\"}" \
      "$BRIDGE_URL/api/users" | python3 -c "import sys,json; d=json.load(sys.stdin); exit(0 if d.get('success') else 1)" \
      || fail "provision $U + $D"
    ok "provision $U + $D"
  done

  LIST=$(curl -sf "${HDR[@]}" "$BRIDGE_URL/api/users")
  echo "$LIST" | grep -q "$USER1" && echo "$LIST" | grep -q "$USER2" || fail "verify multidomain platform"
  ok "verify multidomain platform (2 contas)"

  for U in "$USER1" "$USER2"; do
    curl -sf -X DELETE "${HDR[@]}" "$BRIDGE_URL/api/users/$U" | python3 -c "import sys,json; d=json.load(sys.stdin); exit(0 if d.get('success') else 1)" \
      || fail "cleanup $U"
    ok "cleanup $U"
  done
  RESULT='{"ok":true,"suite":"openpanel-multidomain-api-confirm","mode":"bridge"}'
fi

echo "$RESULT" | python3 -m json.tool
echo "$RESULT" | python3 -c "import sys,json; d=json.load(sys.stdin); sys.exit(0 if d.get('ok') else 1)" \
  && ok "TESTE CONCLUÍDO — OpenPanel multidomínio confirmado" \
  || fail "um ou mais passos falharam"
