import type { Extension, HealthcareService } from 'fhir/r4'; // The form->FHIR transform (`transformToFhirHealthcareService`) maps form FIELDS only; FHIR extensions // are not form fields, so the transform never emits an `extension` array. Feature data lives there - // per-service appointment duration, patient-self-bookable default, and price - each written by its own // editor via an immutable filter-then-append helper. When a service is re-saved through an editor that // does NOT own those features (the full HealthcareService editor, the simple modal), the transform output // has no extensions, so without this the existing ones are silently wiped on save. // // Carry the source resource's extensions onto a freshly-transformed resource before the save. Merge, don't // clobber: any extension the transform already set wins by `url` (today it sets none), and the source's // remaining extensions are appended. Feature helpers (e.g. `applyServicePrice`) still run AFTER this and // filter-then-append their own extension, so the value the user just edited replaces the carried-over one. export const preserveHealthcareServiceExtensions = ( next: HealthcareService, source?: HealthcareService | null, ): HealthcareService => { const sourceExtensions = source?.extension ?? []; if (sourceExtensions.length === 0) { return next; } const nextExtensions = next.extension ?? []; const nextUrls = new Set(nextExtensions.map((extension) => extension.url)); const carried = sourceExtensions.filter((extension) => !nextUrls.has(extension.url)); const merged: Extension[] = [...nextExtensions, ...carried]; return merged.length > 0 ? { ...next, extension: merged } : next; };