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

# Zyphon Gateway Smoke Test
echo "=================================================="
echo "          ZYPHON GATEWAY SMOKE TEST SUITE         "
echo "=================================================="

GATEWAY_URL="${GATEWAY_URL:-http://127.0.0.1:8080}"
ADMIN_URL="${ADMIN_URL:-http://127.0.0.1:8081}"

echo "[1/4] Probing Public Health Endpoint (${GATEWAY_URL}/api/v1/health)..."
HEALTH_STATUS=$(curl -s -o /dev/null -w "%{http_code}" "${GATEWAY_URL}/api/v1/health" || echo "000")
if [ "$HEALTH_STATUS" != "200" ]; then
  echo "✗ Gateway is not responding with 200 OK (HTTP status: ${HEALTH_STATUS})"
  echo "  Make sure gateway is running (e.g. pnpm --filter @zyphon/gateway start)"
  exit 1
fi
echo "✓ Public API is healthy (HTTP 200)"

echo "[2/4] Probing Admin Health Endpoint (${ADMIN_URL}/admin/health)..."
ADMIN_HEALTH_STATUS=$(curl -s -o /dev/null -w "%{http_code}" "${ADMIN_URL}/admin/health" || echo "000")
if [ "$ADMIN_HEALTH_STATUS" != "200" ]; then
  echo "✗ Admin API is not responding with 200 OK (HTTP status: ${ADMIN_HEALTH_STATUS})"
  exit 1
fi
echo "✓ Admin API is healthy (HTTP 200)"

echo "[3/4] Verifying Unauthenticated Request Rejection (Fail-Closed)..."
AUTH_CHECK_STATUS=$(curl -s -o /dev/null -w "%{http_code}" -X POST "${GATEWAY_URL}/api/v1/messages" \
  -H "Content-Type: application/json" \
  -d '{"channel":"email","recipient":"test@example.com","content":{"type":"text","body":"hi"}}' || echo "000")

if [ "$AUTH_CHECK_STATUS" != "401" ]; then
  echo "✗ Expected 401 Unauthorized, got: ${AUTH_CHECK_STATUS}"
  exit 1
fi
echo "✓ Unauthenticated request rejected with HTTP 401"

echo "[4/4] Verifying Prometheus Metrics Endpoint (${GATEWAY_URL}/metrics)..."
METRICS_CONTENT=$(curl -s "${GATEWAY_URL}/metrics")
if echo "$METRICS_CONTENT" | grep -q "zyphon_messages_total"; then
  echo "✓ Prometheus metrics exposition verified"
else
  echo "✗ Metrics format missing expected zyphon_messages_total counter"
  exit 1
fi

echo ""
echo "=================================================="
echo "✓ ALL SMOKE TESTS PASSED CLEANLY!"
echo "=================================================="

