#!/usr/bin/env bash
# Verifica spec 003 — company gate + webmail release (portal + Ops webhook)
set -euo pipefail

OPS_URL="${OPS_URL:-http://127.0.0.1:8080}"
PORTAL_URL="${PORTAL_URL:-http://127.0.0.1:8090}"
WEBHOOK_SECRET="${WEBHOOK_SECRET:-ligbox-ops-dev-secret}"
TEST_DOMAIN="${GATE_TEST_DOMAIN:-example-gate.test}"
SESSION_ID="gate-verify-$(date +%s)"

echo "=== 003 company gate verify ==="
echo "Ops: $OPS_URL | Portal: $PORTAL_URL"

echo "[1] Ops health"
curl -sf "$OPS_URL/health" | python3 -c "import sys,json; d=json.load(sys.stdin); assert d.get('version','').startswith('0.5'), d"

echo "[2] company.validated webhook"
curl -sf -X POST "$OPS_URL/api/v1/webhooks/onboard" \
  -H "Content-Type: application/json" \
  -H "X-Webhook-Secret: $WEBHOOK_SECRET" \
  -d "{
    \"event\": \"company.validated\",
    \"session_id\": \"$SESSION_ID\",
    \"domain\": \"$TEST_DOMAIN\",
    \"data\": {
      \"company_profile\": {
        \"legal_name\": \"Test Gate Ltd\",
        \"domain\": \"$TEST_DOMAIN\",
        \"admin_email\": \"admin@$TEST_DOMAIN\"
      },
      \"billing_state\": \"awaiting_billing_validation\",
      \"webmail_released\": false
    }
  }" | python3 -m json.tool

echo "[3] webmail.released webhook"
curl -sf -X POST "$OPS_URL/api/v1/webhooks/onboard" \
  -H "Content-Type: application/json" \
  -H "X-Webhook-Secret: $WEBHOOK_SECRET" \
  -d "{
    \"event\": \"webmail.released\",
    \"session_id\": \"$SESSION_ID\",
    \"domain\": \"$TEST_DOMAIN\",
    \"data\": {
      \"webmail_released_at\": \"2026-06-08T20:00:00Z\",
      \"released_by_login\": \"11999998888\",
      \"webmail_url\": \"https://mail.$TEST_DOMAIN/\"
    }
  }" | python3 -m json.tool

echo "[4] Portal internal webmail-gate (403 expected if domain unknown/unreleased)"
code=$(curl -s -o /tmp/gate-check.json -w "%{http_code}" \
  "$PORTAL_URL/api/internal/webmail-gate/check?host=mail.$TEST_DOMAIN" \
  -H "X-Internal-Secret: ${WEBMAIL_GATE_INTERNAL_SECRET:-ligbox-webmail-gate-dev}" || true)
echo "HTTP $code"
cat /tmp/gate-check.json 2>/dev/null | python3 -m json.tool || true

echo "=== OK ==="
