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

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"

echo "==> Build contracts"
dotnet build VigilCare.ClinicalContracts

echo "==> Run gateway registry tests"
dotnet test VigilCareClinicalAPI.Tests --filter "FullyQualifiedName~GatewayRegistry" --no-build 2>/dev/null \
  || dotnet test VigilCareClinicalAPI.Tests --filter "FullyQualifiedName~GatewayRegistry"

API="${API_BASE_URL:-http://localhost:5270}"
KEY="${GATEWAY_API_KEY:-dev-gateway-key-change-in-production}"

# Obtain admin JWT (adjust to your local login endpoint)
TOKEN="${ADMIN_JWT:?Set ADMIN_JWT to a valid admin bearer token}"

echo "==> Create site"
SITE_RESP=$(curl -sf -X POST "$API/api/v1/sites" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"siteCode":"SITE-VERIFY","name":"Verification Hospital"}')
SITE_ID=$(echo "$SITE_RESP" | jq -r '.data.id')

echo "==> Register gateway"
GW_RESP=$(curl -sf -X POST "$API/api/v1/sites/$SITE_ID/gateways" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"gatewayCode":"GW-VERIFY-01","department":"ICU"}')
GW_ID=$(echo "$GW_RESP" | jq -r '.data.id')

echo "==> Heartbeat"
curl -sf -X PATCH "$API/api/v1/gateways/$GW_ID/heartbeat" \
  -H "X-Api-Key: $KEY" \
  -H "X-Gateway-Id: $GW_ID" \
  -H "Content-Type: application/json" \
  -d '{"status":"ONLINE","bufferDepth":3,"reportedAtUtc":"'"$(date -u +%Y-%m-%dT%H:%M:%SZ)"'"}'

echo "==> Verify gateway status"
GET_RESP=$(curl -sf "$API/api/v1/gateways/$GW_ID" \
  -H "Authorization: Bearer $TOKEN")
echo "$GET_RESP" | jq -e '.data.status == "ONLINE" and .data.reportedBufferDepth == 3'

echo "Phase 20 verification passed."