#!/bin/bash
# Sprint 2 tests: PR #35 — Proactive Engine + CRM API
BASE="http://localhost:3099"
PASS=0 FAIL=0 TOTAL=0

t() {
  TOTAL=$((TOTAL + 1))
  if echo "$3" | grep -q "$2"; then
    PASS=$((PASS + 1)); echo "  ✅ $1"
  else
    FAIL=$((FAIL + 1)); echo "  ❌ $1 (expected: $2, got: $3)"
  fi
}

# Auth
R=$(curl -s "$BASE/api/auth/signup" -X POST -H 'Content-Type: application/json' \
  -d "{\"name\":\"ProTest\",\"email\":\"pro-$RANDOM@t.com\",\"password\":\"test123\"}")
TOKEN=$(echo "$R" | grep -o '"token":"[^"]*"' | cut -d'"' -f4)
AUTH="Authorization: Bearer $TOKEN"

echo "=== PROACTIVE ENGINE API ==="

R=$(curl -s -w "\n%{http_code}" -H "$AUTH" "$BASE/api/admin/proactive/config")
t "GET config → 200" "200" "$(echo "$R" | tail -1)"
t "config has 6 triggers" "weekly_report" "$(echo "$R" | head -1)"

R=$(curl -s -w "\n%{http_code}" -H "$AUTH" "$BASE/api/admin/proactive/logs")
t "GET logs → 200" "200" "$(echo "$R" | tail -1)"

R=$(curl -s -w "\n%{http_code}" -H "$AUTH" "$BASE/api/admin/proactive/stats")
t "GET stats → 200" "200" "$(echo "$R" | tail -1)"

R=$(curl -s -w "\n%{http_code}" -H "$AUTH" -X POST "$BASE/api/admin/proactive/run")
t "POST run → 200" "200" "$(echo "$R" | tail -1)"

# No auth
R=$(curl -s -w "\n%{http_code}" "$BASE/api/admin/proactive/config")
t "config without auth → 401" "401" "$(echo "$R" | tail -1)"

echo ""
echo "=== CRM API ==="

R=$(curl -s -w "\n%{http_code}" -H "$AUTH" "$BASE/api/crm/segments")
t "GET segments → 200" "200" "$(echo "$R" | tail -1)"
t "segments has data" "segments" "$(echo "$R" | head -1)"

R=$(curl -s -w "\n%{http_code}" -H "$AUTH" "$BASE/api/crm/clients/1/ltv")
t "GET client LTV (not found) → 404" "404" "$(echo "$R" | tail -1)"

R=$(curl -s -w "\n%{http_code}" "$BASE/api/crm/segments")
t "crm without auth → 401" "401" "$(echo "$R" | tail -1)"

echo ""
echo "=== UNIT TESTS (PR #35) ==="
cd /home/ubuntu/belezapro-ai/backend
UNIT=$(JWT_SECRET=test-secret node tests/proactiveEngine.test.js 2>&1)
UNIT_PASS=$(echo "$UNIT" | grep "^# pass" | awk '{print $3}')
UNIT_FAIL=$(echo "$UNIT" | grep "^# fail" | awk '{print $3}')
echo "  Unit: $UNIT_PASS pass, $UNIT_FAIL fail"
if [ "$UNIT_FAIL" = "0" ]; then
  PASS=$((PASS + 1)); TOTAL=$((TOTAL + 1)); echo "  ✅ All $UNIT_PASS unit tests pass"
else
  FAIL=$((FAIL + 1)); TOTAL=$((TOTAL + 1)); echo "  ❌ $UNIT_FAIL unit tests failed"
fi

echo ""
echo "=== RESULTS ==="
echo "Total: $TOTAL | Pass: $PASS | Fail: $FAIL"
[ "$FAIL" -eq 0 ] && echo "🟢 ALL PASS" || echo "🔴 $FAIL FAILURES"
