#!/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="verify-$(date +%s)"
DOMAIN="verify.ops.ligbox"

echo "=== Ligbox Ops Webhook Verification ==="
echo "OPS_URL=$OPS_URL"

echo "[1] Health"
curl -sf "$OPS_URL/health" | python3 -m json.tool

echo "[2] Send account.created"
curl -sf -X POST "$OPS_URL/api/v1/webhooks/onboard" \
  -H "Content-Type: application/json" \
  -H "X-Webhook-Secret: $SECRET" \
  -d "{\"event\":\"account.created\",\"domain\":\"$DOMAIN\",\"session_id\":\"$SESSION_ID\",\"data\":{\"email\":\"admin@$DOMAIN\",\"account_verified\":true,\"needs_review\":false}}" \
  | python3 -m json.tool

echo "[3] Duplicate (expect duplicate=true, no new ticket)"
curl -sf -X POST "$OPS_URL/api/v1/webhooks/onboard" \
  -H "Content-Type: application/json" \
  -H "X-Webhook-Secret: $SECRET" \
  -d "{\"event\":\"account.created\",\"domain\":\"$DOMAIN\",\"session_id\":\"$SESSION_ID\",\"data\":{\"email\":\"admin@$DOMAIN\",\"account_verified\":true,\"needs_review\":false}}" \
  | python3 -m json.tool

echo "[4] Invalid secret (expect 401)"
if curl -sf -X POST "$OPS_URL/api/v1/webhooks/onboard" \
  -H "Content-Type: application/json" \
  -H "X-Webhook-Secret: wrong-secret" \
  -d "{\"event\":\"account.created\",\"domain\":\"$DOMAIN\",\"session_id\":\"bad\"}"; then
  echo "FAIL: expected 401"
  exit 1
else
  echo "OK: rejected invalid secret"
fi

echo "[5] Tickets"
curl -sf "$OPS_URL/api/v1/desk/tickets" | python3 -m json.tool | head -30

echo "=== Verification complete ==="
