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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"

echo "=== Phase 30 verification ==="

echo "1. Integration tests"
dotnet test "${ROOT_DIR}/VigilCareClinicalAPI.Tests" \
  --filter "FullyQualifiedName~FhirIngest" \
  --no-restore

echo "2. Manual FHIR checks (requires running stack)"
BASE_URL="${BASE_URL:-http://localhost:5270}"
API_KEY="${API_KEY:-dev-integration-key-change-in-production}"

fhir_post() {
  local path="$1" body="$2"
  curl -sf -X POST "${BASE_URL}${path}" \
    -H "Content-Type: application/fhir+json" \
    -H "X-Api-Key: ${API_KEY}" \
    -d "${body}"
}

echo "2a. CapabilityStatement"
curl -sf "${BASE_URL}/fhir/R4/metadata" -H "X-Api-Key: ${API_KEY}" | jq -e '.resourceType == "CapabilityStatement"'

echo "2b. Admit transaction bundle"
fhir_post "/fhir/R4" '{
  "resourceType": "Bundle",
  "type": "transaction",
  "entry": [
    {
      "resource": {
        "resourceType": "Patient",
        "identifier": [{ "system": "http://hospital.example/mrn", "value": "MRN-VERIFY-001" }],
        "name": [{ "family": "Verify", "given": ["Phase30"] }],
        "birthDate": "1975-06-01",
        "gender": "male"
      },
      "request": { "method": "POST", "url": "Patient" }
    },
    {
      "resource": {
        "resourceType": "Encounter",
        "status": "in-progress",
        "class": { "system": "http://terminology.hl7.org/CodeSystem/v3-ActCode", "code": "IMP" },
        "identifier": [{ "system": "http://hospital.example/visit", "value": "VISIT-VERIFY-001" }],
        "subject": { "identifier": { "system": "http://hospital.example/mrn", "value": "MRN-VERIFY-001" } },
        "participant": [{ "individual": { "display": "Dr. Verify" } }]
      },
      "request": { "method": "POST", "url": "Encounter" }
    }
  ]
}' | jq -e '.type == "transaction-response"'

echo "Phase 30 verification complete."