import { Appointment, Bundle, Slot } from 'fhir/r4'; import { useEffect } from 'react'; import { usePatientServiceContext, useWebSocketServiceContext } from '../services'; interface UseFhirAppointmentTargetedBroadcastOptions { appointment?: Appointment; appointmentId?: string; isOpen?: boolean; onUpdate: (appointment: Appointment) => void; onDelete: () => void; } export const useFhirAppointmentTargetedBroadcast = ({ appointment, appointmentId, isOpen = true, onUpdate, onDelete }: UseFhirAppointmentTargetedBroadcastOptions) => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); const { patientState } = usePatientServiceContext(); useEffect(() => { if (!patientState || !appointment || !isOpen) { 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; const targetId = appointmentId || appointment.id; if (!appointmentPayload) { console.warn('No appointment found in broadcast bundle'); return; } if (appointmentPayload.id === targetId) { switch (eventType) { case 'com.akashichealthrecords.fhir.appointment.updated': onUpdate(appointmentPayload); break; case 'com.akashichealthrecords.fhir.appointment.deleted': onDelete() break; } } }; subscribe('com.akashichealthrecords.fhir.appointment.updated', handleAppointmentEvent); subscribe('com.akashichealthrecords.fhir.appointment.deleted', handleAppointmentEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.appointment.updated', handleAppointmentEvent); unsubscribe('com.akashichealthrecords.fhir.appointment.deleted', handleAppointmentEvent); }; }, [patientState, appointment, appointmentId, isOpen, onUpdate, onDelete, subscribe, unsubscribe]); };