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

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

CENTRAL="${CENTRAL_URL:-http://localhost:5270}"
GATEWAY="${GATEWAY_URL:-http://localhost:5081}"
KEY="${GATEWAY_API_KEY:-dev-gateway-key-change-in-production}"
GW_ID="${GATEWAY_ID:-22222222-2222-2222-2222-222222222222}"
JWT="${ADMIN_JWT:?Set ADMIN_JWT}"

echo "==> Start full stack"
docker compose --profile full --profile ward-gateway up -d
sleep 30

echo "==> Stop central API to buffer events on gateway"
# Stop only central API process/container — gateway stack stays up

ENCOUNTER_ID=$(curl -sf "$GATEWAY/api/v1/encounters?status=ACTIVE&department=ICU" \
  -H "Authorization: Bearer ${GATEWAY_JWT:?Set GATEWAY_JWT}" | jq -r '.data.items[0].encounterId')

echo "==> Post observations to gateway while central down"
for i in $(seq 1 10); do
  curl -sf -X POST "$GATEWAY/api/v1/encounters/$ENCOUNTER_ID/observations" \
    -H "Authorization: Bearer $GATEWAY_JWT" \
    -H "Content-Type: application/json" \
    -d "{\"observationCode\":\"HEART_RATE\",\"value\":$((100+i)),\"unit\":\"bpm\",\"source\":\"DEVICE\",\"recordedAt\":\"$(date -u +%Y-%m-%dT%H:%M:%SZ)\",\"idempotencyKey\":\"verify-$i\"}" \
    > /dev/null
done

echo "==> Restart central and wait for sync"
# Start central API; poll gateway buffer depth → 0

echo "==> Poll batch status"
BATCH_ID=$(curl -sf "$CENTRAL/api/v1/sites/11111111-1111-1111-1111-111111111111/gateways/$GW_ID/sync-history" \
  -H "Authorization: Bearer $JWT" | jq -r '.data[0].batchId')
curl -sf "$CENTRAL/api/v1/sync/batches/$BATCH_ID" \
  -H "Authorization: Bearer $JWT" | jq -e '.data.status == "APPLIED"'

echo "==> Verify observations on central"
curl -sf "$CENTRAL/api/v1/encounters/$ENCOUNTER_ID/observations" \
  -H "Authorization: Bearer $JWT" | jq -e '.data.items | length >= 10'

echo "==> Verify client_alert_id populated"
docker exec -i $(docker ps -qf name=postgres) psql -U postgres -d vigilcare \
  -c "SELECT COUNT(*) FROM clinical_alerts WHERE client_alert_id IS NOT NULL;" | grep -v "^-" | grep -v row | awk '{print $1}' | grep -v '^0$'

echo "==> Check no duplicate paging (grep application logs for [PAGE] count)"
echo "Phase 22 verification passed."
