#!/usr/bin/env bash
# verify-gateway.sh — smoke-test the gateway without touching upstream.
#
# Validates:
#   1. /health returns 200 without auth
#   2. /v1/messages without token returns 401
#   3. /v1/messages with wrong token returns 401
#   4. /v1/messages with correct token forwards upstream (will get 401 from
#      upstream if UPSTREAM_API_KEY is wrong — that's fine, it proves the
#      proxy chain works end-to-end)
#
# Run gateway first:
#   ( cd gateway && npm run dev ) &
#   bash scripts/verify-gateway.sh
set -euo pipefail

PORT="${PORT:-4290}"
TOKEN="${GATEWAY_TOKEN:-demo-token-change-me}"
BASE="http://localhost:${PORT}"

echo "[verify] base = ${BASE}"

pass=0
fail=0

check() {
  local label="$1" expected="$2" actual="$3"
  if [[ "${actual}" == "${expected}" ]]; then
    echo "  ✅ ${label}: ${actual}"
    pass=$((pass+1))
  else
    echo "  ❌ ${label}: expected ${expected}, got ${actual}"
    fail=$((fail+1))
  fi
}

# 1. health
code=$(curl -s -o /dev/null -w "%{http_code}" "${BASE}/health")
check "GET /health" "200" "${code}"

# 2. no auth → 401
code=$(curl -s -o /dev/null -w "%{http_code}" -X POST "${BASE}/v1/messages" \
  -H 'content-type: application/json' \
  -d '{"model":"claude-sonnet-4-6","max_tokens":16,"messages":[{"role":"user","content":"hi"}]}')
check "POST /v1/messages (no auth)" "401" "${code}"

# 3. wrong token → 401
code=$(curl -s -o /dev/null -w "%{http_code}" -X POST "${BASE}/v1/messages" \
  -H 'content-type: application/json' \
  -H 'x-gateway-token: WRONG' \
  -d '{"model":"claude-sonnet-4-6","max_tokens":16,"messages":[{"role":"user","content":"hi"}]}')
check "POST /v1/messages (wrong token)" "401" "${code}"

# 4. correct token → upstream response (likely 401 from upstream if key bad)
echo "[verify] forwarding upstream (response body shown):"
curl -sS -X POST "${BASE}/v1/messages" \
  -H 'content-type: application/json' \
  -H "x-gateway-token: ${TOKEN}" \
  -d '{"model":"claude-sonnet-4-6","max_tokens":16,"messages":[{"role":"user","content":"hi"}]}' | head -c 400
echo ""
echo ""

echo "[verify] passed=${pass} failed=${fail}"
exit "${fail}"
