#!/usr/bin/env bash
set -euo pipefail

ENV_FILE="${ENV_FILE:-/opt/ligbox-ops-platform/.env}"
if [[ -f "$ENV_FILE" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$ENV_FILE"
  set +a
fi

OPS_URL="${OPS_URL:-http://10.10.10.122:8080}"
SECRET="${WEBHOOK_SECRET:-ligbox-ops-dev-secret}"
INTERNAL="${OPS_INTERNAL_TOKEN:?OPS_INTERNAL_TOKEN required}"
SESSION_ID="lead-verify-$(date +%s)"
DOMAIN="lead.ops.ligbox"
DESK_PASS="${DESK_BOOTSTRAP_PASSWORD:-805353}"

post_event() {
  local event="$1"
  local extra="$2"
  curl -sf -X POST "$OPS_URL/api/v1/webhooks/onboard" \
    -H "Content-Type: application/json" \
    -H "X-Webhook-Secret: $SECRET" \
    -d "{\"event\":\"$event\",\"domain\":\"$DOMAIN\",\"session_id\":\"$SESSION_ID\",\"data\":$extra}"
}

echo "=== Spec 012 — CRM Leads (Fase B) ==="
echo "SESSION_ID=$SESSION_ID"

echo "[1] Health"
curl -sf "$OPS_URL/health" | python3 -m json.tool | grep -E 'version|status'

echo "[2] Create onboarding ticket (create_account step)"
post_event "onboarding.started" '{"email":"lead-test@ops.ligbox","step":"create_account"}' \
  | python3 -c "import sys,json; d=json.load(sys.stdin); assert d.get('ticket_created'); print('ticket_id=', d.get('ticket_id'))"

echo "[3] Promote stale → lead (stale_hours=0 for test)"
SYNC=$(curl -sf -X POST "$OPS_URL/api/v1/crm/leads/sync?stale_hours=0" \
  -H "X-Ops-Internal-Token: $INTERNAL")
echo "$SYNC" | python3 -m json.tool
python3 -c "import sys,json; d=json.loads('''$SYNC'''); assert d.get('promoted',0)>=1, d; print('OK promoted', d['promoted'])"

echo "[4] List leads (JWT)"
TOKEN=$(curl -sf -X POST "$OPS_URL/api/v1/auth/login" \
  -H "Content-Type: application/json" \
  -d "{\"username\":\"root\",\"password\":\"$DESK_PASS\"}" \
  | python3 -c "import sys,json; print(json.load(sys.stdin)['access_token'])")
curl -sf -H "Authorization: Bearer $TOKEN" "$OPS_URL/api/v1/crm/leads" \
  | python3 -c "
import sys,json
d=json.load(sys.stdin)
ids=[x['session_id'] for x in d.get('leads',[])]
assert '$SESSION_ID' in ids or any('$SESSION_ID' in (x or '') for x in ids), d
print('OK leads total=', d.get('total'))
"

echo "=== CRM Leads verification complete ==="
