import { usePatientServiceContext, useWebSocketServiceContext } from '../services'; import { useEffect } from 'react'; import { Appointment, Bundle, Slot } from 'fhir/r4'; interface UseFhirAppointmentBroadcastOptions { onCreate: (appointment: Appointment) => void; onUpdate: (appointment: Appointment) => void; onDelete: (appointment: Appointment) => void; } export const useFhirAppointmentBroadcast = ({ onCreate, onUpdate, onDelete }: UseFhirAppointmentBroadcastOptions) => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); const { patientState } = usePatientServiceContext(); useEffect(() => { if (!patientState) { return; } const handleAppointmentEvent = (cloudEvent: any) => { const bundle: Bundle = cloudEvent.data; const eventType = cloudEvent.type; const appointmentPayload: Appointment = bundle.entry?.find(e => e.resource?.resourceType === 'Appointment')?.resource as Appointment; if (!appointmentPayload) { console.warn('No appointment found in broadcast bundle'); return; } switch (eventType) { case 'com.akashichealthrecords.fhir.appointment.created': onCreate(appointmentPayload); break; case 'com.akashichealthrecords.fhir.appointment.updated': onUpdate(appointmentPayload); break; case 'com.akashichealthrecords.fhir.appointment.deleted': onDelete(appointmentPayload) break; } }; subscribe('com.akashichealthrecords.fhir.appointment.created', handleAppointmentEvent); subscribe('com.akashichealthrecords.fhir.appointment.updated', handleAppointmentEvent); subscribe('com.akashichealthrecords.fhir.appointment.deleted', handleAppointmentEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.appointment.created', handleAppointmentEvent); unsubscribe('com.akashichealthrecords.fhir.appointment.updated', handleAppointmentEvent); unsubscribe('com.akashichealthrecords.fhir.appointment.deleted', handleAppointmentEvent); }; }, [patientState, onCreate, onUpdate, onDelete, subscribe, unsubscribe]); };