#!/bin/bash
# BelezaPro AI — Full E2E Test Suite (v2 — fixed parsing)
BASE="http://localhost:3099"
PASS=0; FAIL=0; TOTAL=0

t() {
  TOTAL=$((TOTAL+1))
  local name="$1" method="$2" url="$3" data="$4" expect_code="$5" expect_body="$6" extra_headers="$7"
  
  local tmpf=$(mktemp)
  local args=(-s -o "$tmpf" -w "%{http_code}" -X "$method")
  [ -n "$data" ] && args+=(-H "Content-Type: application/json" -d "$data")
  [ -n "$extra_headers" ] && args+=(-H "$extra_headers")
  
  local code
  code=$(curl "${args[@]}" "$BASE$url" 2>/dev/null)
  local body
  body=$(cat "$tmpf")
  rm -f "$tmpf"
  
  local ok=true
  [ "$code" != "$expect_code" ] && ok=false
  [ -n "$expect_body" ] && ! echo "$body" | grep -q "$expect_body" && ok=false
  
  if $ok; then
    echo "✅ #$TOTAL $name (HTTP $code)"
    PASS=$((PASS+1))
  else
    echo "❌ #$TOTAL $name — expected $expect_code, got $code"
    [ -n "$expect_body" ] && echo "   expected body match: '$expect_body'"
    echo "   body: $(echo "$body" | head -1 | cut -c1-120)"
    FAIL=$((FAIL+1))
  fi
}

echo "============================================"
echo "  BelezaPro AI — E2E Test Suite v2"
echo "  $(date -u '+%Y-%m-%d %H:%M UTC')"
echo "============================================"

# ─── 1. HEALTH ───
echo -e "\n── 1. Health ──"
t "Health check" GET "/api/health" "" "200" "ok"

# ─── 2. AUTH ───
echo -e "\n── 2. Auth ──"
TS=$(date +%s)
SIGNUP="{\"name\":\"E2E Salon $TS\",\"email\":\"e2e-$TS@test.com\",\"password\":\"Test1234!\",\"phone\":\"55119$TS\"}"
t "Signup new user" POST "/api/auth/signup" "$SIGNUP" "201" "token"

# get token via login
LOGIN="{\"email\":\"e2e-$TS@test.com\",\"password\":\"Test1234!\"}"
tmptoken=$(mktemp)
curl -s -o "$tmptoken" -X POST -H "Content-Type: application/json" -d "$LOGIN" "$BASE/api/auth/login" 2>/dev/null
TOKEN=$(cat "$tmptoken" | python3 -c "import sys,json; print(json.load(sys.stdin).get('token',''))" 2>/dev/null)
rm -f "$tmptoken"
[ -z "$TOKEN" ] && echo "❌ FATAL: no token" && exit 1
echo "   🔑 Token: ${TOKEN:0:20}..."
AUTH="Authorization: Bearer $TOKEN"

t "Login valid" POST "/api/auth/login" "$LOGIN" "200" "token"
t "Login wrong pw" POST "/api/auth/login" "{\"email\":\"e2e-$TS@test.com\",\"password\":\"wrong\"}" "401" ""
t "No token → 401" GET "/api/clients" "" "401" ""
t "Signup duplicate" POST "/api/auth/signup" "$SIGNUP" "409" ""

# ─── 3. SERVICES ───
echo -e "\n── 3. Services ──"
t "Create service" POST "/api/services" '{"name":"Corte Feminino","duration_minutes":60,"price":80}' "201" "" "$AUTH"
t "List services" GET "/api/services" "" "200" "Corte" "$AUTH"

# get svc id
SVC_ID=$(curl -s -H "$AUTH" "$BASE/api/services" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d[-1]['id'] if d else '')" 2>/dev/null)

# ─── 4. CLIENTS ───
echo -e "\n── 4. Clients ──"
t "Create client" POST "/api/clients" '{"name":"Maria E2E","phone":"5511988880099","whatsapp":"5511988880099"}' "201" "" "$AUTH"
t "List clients" GET "/api/clients" "" "200" "Maria" "$AUTH"
t "Reactivation" GET "/api/clients/reactivation" "" "200" "" "$AUTH"

CLI_ID=$(curl -s -H "$AUTH" "$BASE/api/clients" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d[-1]['id'] if d else '')" 2>/dev/null)

# ─── 5. APPOINTMENTS ───
echo -e "\n── 5. Appointments ──"
TOMORROW=$(date -u -d "+1 day" '+%Y-%m-%d')
APPT="{\"client_id\":$CLI_ID,\"service_id\":$SVC_ID,\"date\":\"$TOMORROW\",\"time\":\"14:00\",\"notes\":\"E2E\"}"
t "Create appointment" POST "/api/appointments" "$APPT" "201" "" "$AUTH"
t "List appointments" GET "/api/appointments" "" "200" "" "$AUTH"
t "Today" GET "/api/appointments/today" "" "200" "" "$AUTH"
t "Week" GET "/api/appointments/week" "" "200" "" "$AUTH"
t "Slots" GET "/api/appointments/available-slots?date=$TOMORROW&service_id=$SVC_ID" "" "200" "" "$AUTH"

# ─── 6. MESSAGES ───
echo -e "\n── 6. Messages ──"
t "List messages" GET "/api/messages" "" "200" "" "$AUTH"
t "Conversations" GET "/api/messages/conversations" "" "200" "" "$AUTH"

# ─── 7. CAMPAIGNS ───
echo -e "\n── 7. Campaigns ──"
t "Create campaign" POST "/api/campaigns" '{"name":"Test Camp","type":"reactivation","message_template":"Volta!","target_segment":"inactive"}' "201" "" "$AUTH"
t "List campaigns" GET "/api/campaigns" "" "200" "" "$AUTH"

# ─── 8. PROFESSIONALS ───
echo -e "\n── 8. Professionals ──"
t "List professionals" GET "/api/professionals" "" "200" "" "$AUTH"

PRO_ID=$(curl -s -H "$AUTH" "$BASE/api/professionals" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d[0]['id'] if d else '')" 2>/dev/null)
[ -n "$PRO_ID" ] && t "Dashboard" GET "/api/professionals/$PRO_ID/dashboard" "" "200" "" "$AUTH"

# ─── 9. STATIC PAGES ───
echo -e "\n── 9. Static Pages ──"
t "Site landing" GET "/site/" "" "200" "BelezaPro"
t "Admin panel" GET "/admin/" "" "200" "html"
t "Onboarding" GET "/onboarding/" "" "200" "html"
t "Pitch deck" GET "/pitch/" "" "200" "html"
t "Playground" GET "/playground/" "" "200" "html"

# ─── 10. OBSERVABILITY (Batch 4) ───
echo -e "\n── 10. Observability ──"
t "LLM metrics (non-admin)" GET "/api/admin/metrics/llm" "" "403" "" "$AUTH"
t "Observability conversations (non-admin)" GET "/api/admin/metrics/conversations" "" "403" "" "$AUTH"

# ─── 11. PLAYGROUND API ───
echo -e "\n── 11. Playground API ──"
t "Playground chat" POST "/api/agent/message" '{"channel":"playground","from":"5511999990099","message":"Oi"}' "200" "" "$AUTH"

# ─── 12. AGENT ───
echo -e "\n── 12. Agent ──"
t "Agent chat" POST "/api/agent/message" '{"channel":"whatsapp","from":"5511999990099","message":"Serviços?"}' "200" "" "$AUTH"

# ─── 13. WEBHOOK ───
echo -e "\n── 13. WhatsApp Webhook ──"
t "Webhook (no auth)" POST "/api/whatsapp/webhook" '{"from":"5511999990099","message":"Oi"}' "401" ""
t "Webhook (with auth)" POST "/api/whatsapp/webhook" '{"from":"5511999990099","message":"Oi"}' "200" "" "$AUTH"

# ─── 14. MULTI-TENANT ───
echo -e "\n── 14. Multi-tenant Isolation ──"
TS2=$(date +%s%N | cut -c1-13)
SIGNUP2="{\"name\":\"Tenant2\",\"email\":\"t2-$TS2@test.com\",\"password\":\"Test1234!\"}"
tmptoken2=$(mktemp)
curl -s -o "$tmptoken2" -X POST -H "Content-Type: application/json" -d "$SIGNUP2" "$BASE/api/auth/signup" 2>/dev/null
TOKEN2=$(cat "$tmptoken2" | python3 -c "import sys,json; print(json.load(sys.stdin).get('token',''))" 2>/dev/null)
rm -f "$tmptoken2"

if [ -n "$TOKEN2" ]; then
  AUTH2="Authorization: Bearer $TOKEN2"
  CLIENTS2=$(curl -s -H "$AUTH2" "$BASE/api/clients")
  if echo "$CLIENTS2" | grep -q "Maria E2E"; then
    echo "❌ #$((++TOTAL)) Tenant isolation BROKEN"; FAIL=$((FAIL+1))
  else
    echo "✅ #$((++TOTAL)) Tenant isolation OK"; PASS=$((PASS+1))
  fi
else
  echo "⚠️  Skipped (couldn't create tenant 2)"
fi

# ─── SUMMARY ───
echo ""
echo "============================================"
PCT=$((PASS * 100 / TOTAL))
echo "  RESULTS: $PASS/$TOTAL passed ($PCT%), $FAIL failed"
if [ $FAIL -eq 0 ]; then
  echo "  🟢 ALL CLEAR"
else
  echo "  🔴 $FAIL FAILURES"
fi
echo "============================================"
