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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
BASE_URL="${BASE_URL:-http://localhost:5270}"

echo "=== Phase 34 verification ==="

dotnet test "${ROOT_DIR}/VigilCareClinicalAPI.Tests" \
  --filter "FullyQualifiedName~ExplainableAlerts" --no-restore

TOKEN=$(curl -sf -X POST "${BASE_URL}/api/v1/auth/login" \
  -H "Content-Type: application/json" \
  -d '{"username":"admin.demo","password":"DemoAdmin1!"}' \
  | jq -r '.data.accessToken')

ALERT_ID=$(curl -sf "${BASE_URL}/api/v1/alerts?status=OPEN&pageSize=50" \
  -H "Authorization: Bearer ${TOKEN}" \
  | jq -r '[.data.items[] | select(.explanation != null)][0].id // empty')

if [[ -z "${ALERT_ID}" ]]; then
  echo "No open alert with explanation found — run a simulator scenario first, then re-run live checks"
  echo "Phase 34 verification complete (tests only)."
  exit 0
fi

echo "Verify explanation on alert ${ALERT_ID}"
curl -sf "${BASE_URL}/api/v1/alerts/${ALERT_ID}" \
  -H "Authorization: Bearer ${TOKEN}" \
  | jq -e '.data.explanation.narrativeSummary != null'

echo "Verify DB jsonb column"
docker compose exec -T postgres psql -U vigilcare -d vigilcare -c \
  "SELECT id, explanation IS NOT NULL AS has_explanation FROM clinical_alerts WHERE id = '${ALERT_ID}';"

echo "Phase 34 verification complete."
