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

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

echo "=== Phase 32 verification ==="

dotnet test "${ROOT_DIR}/VigilCareClinicalAPI.Tests" \
  --filter "FullyQualifiedName~PhiEncryption" --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')

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

echo "View patient ${PATIENT_ID}"
curl -sf "${BASE_URL}/api/v1/patients/${PATIENT_ID}" \
  -H "Authorization: Bearer ${TOKEN}" | jq -e '.data.firstName != null'

echo "Verify PHI access log"
curl -sf "${BASE_URL}/api/v1/phi-access-logs?patientId=${PATIENT_ID}" \
  -H "Authorization: Bearer ${TOKEN}" | jq -e '.data.totalCount >= 1'

echo "Verify raw DB encryption (requires psql)"
docker compose exec -T postgres psql -U postgres -d vigilcare -c \
  "SELECT id, left(first_name, 20) AS encrypted_prefix FROM patients WHERE id = '${PATIENT_ID}';"

echo "Phase 32 verification complete."