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

OPS_URL="${OPS_URL:-http://10.10.10.122:8080}"
SECRET="${WEBHOOK_SECRET:-ligbox-ops-dev-secret}"
SESSION_ID="funnel-verify-$(date +%s)"
DOMAIN="funnel.ops.ligbox"

post_event() {
  local event="$1"
  local extra="$2"
  if [[ -z "$extra" ]]; then
    extra='{"test":true}'
  fi
  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 "=== Ligbox Ops Funnel Verification (004) ==="
echo "OPS_URL=$OPS_URL SESSION_ID=$SESSION_ID"

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

echo "[2] Funnel events sequence (ordem real VM112: domínio → DNS → criar servidor → conta)"
for ev in domain.validated dns.applied onboarding.started account.created infra.synced onboarding.completed; do
  echo "  -> $ev"
  extra='{"test":true}'
  if [[ "$ev" == "onboarding.started" ]]; then
    extra='{"test":true,"email":"funnel-test@ops.ligbox","step":"create_account"}'
  elif [[ "$ev" == "account.created" ]]; then
    extra='{"test":true,"email":"funnel-test@ops.ligbox"}'
  fi
  post_event "$ev" "$extra" | python3 -c "import sys,json; d=json.load(sys.stdin); print('     duplicate=',d.get('duplicate'),'ticket_created=',d.get('ticket_created'),'ticket_id=',d.get('ticket_id'))"
done

echo "[2b] Ticket must exist after onboarding.started"
DESK_PASS="${DESK_BOOTSTRAP_PASSWORD:-805353}"
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).get('access_token',''))")
curl -sf -H "Authorization: Bearer $TOKEN" \
  "$OPS_URL/api/v1/onboard/sessions/${SESSION_ID}/timeline" | python3 -c "
import sys,json
d=json.load(sys.stdin)
assert d.get('ticket_id'), 'ticket_id missing after onboarding.started'
print('OK ticket_id=', d['ticket_id'])
"

echo "[3] Funnel API"
curl -sf "$OPS_URL/api/v1/onboard/funnel" | python3 -m json.tool | head -40

echo "[4] Timeline API"
curl -sf "$OPS_URL/api/v1/onboard/sessions/${SESSION_ID}/timeline" | python3 -m json.tool | head -35

echo "[5] Duplicate onboarding.started (expect duplicate=true)"
post_event "onboarding.started" '{}' | python3 -c "import sys,json; d=json.load(sys.stdin); assert d.get('duplicate') is True; print('OK duplicate')"

echo "=== Funnel verification complete ==="
