import type { Appointment, Extension } from 'fhir/r4'; // The catalogue service a booking chose, beside its clinical coding. The server reads the same // URL: one top-level Appointment.extension holding a plain local HealthcareService reference. export const SELECTED_SERVICE_EXTENSION_URL = 'https://akashichealthrecords.com/fhir/StructureDefinition/appointment-healthcare-service'; /** The appointment with exactly this selected service; every other extension is kept. */ export function withSelectedServiceRef>(appointment: T, serviceId: string): T { const others = (appointment.extension ?? []).filter((extension) => extension.url !== SELECTED_SERVICE_EXTENSION_URL); const selected: Extension = { url: SELECTED_SERVICE_EXTENSION_URL, valueReference: { reference: `HealthcareService/${serviceId}` } }; return { ...appointment, extension: [...others, selected] }; } /** The id of the one catalogue service this booking recorded choosing, if it recorded exactly one. */ export function selectedServiceIdOf(appointment: Pick | undefined): string | undefined { const carried = (appointment?.extension ?? []).filter((extension) => extension.url === SELECTED_SERVICE_EXTENSION_URL); if (carried.length !== 1) return undefined; return /^HealthcareService\/([A-Za-z0-9\-.]{1,64})$/.exec(carried[0].valueReference?.reference ?? '')?.[1]; }