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

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

echo "=== Phase 33 verification ==="

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

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

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

if [[ "${ALERT_ID}" == "null" || -z "${ALERT_ID}" ]]; then
  echo "No acknowledged alert found — acknowledge one first via simulator or API"
  exit 1
fi

echo "Submit feedback for alert ${ALERT_ID}"
curl -sf -X POST "${BASE_URL}/api/v1/alerts/${ALERT_ID}/feedback" \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{"feedbackType":"Useful","comment":"Phase 33 verification"}' \
  | jq -e '.data.id != null'

echo "Verify quality metrics summary"
curl -sf "${BASE_URL}/api/v1/alerts/quality-metrics/summary" \
  -H "Authorization: Bearer ${TOKEN}" | jq -e '.data.totalAlerts >= 0'

echo "Verify quality metrics list"
curl -sf "${BASE_URL}/api/v1/alerts/quality-metrics?from=$(date -u -d '7 days ago' +%Y-%m-%dT%H:%M:%SZ)" \
  -H "Authorization: Bearer ${TOKEN}" | jq -e '.data.items != null'

echo "Phase 33 verification complete."