import { useEffect } from 'react'; import { Schedule } from 'fhir/r4'; import { useWebSocketServiceContext } from '../services'; interface UseScheduleWebSocketOptions { schedule?: Schedule; scheduleId?: string; isOpen?: boolean; onUpdate: (schedule: Schedule) => void; onDelete: () => void; } export const useFhirScheduleTargetedBroadcast = ({ schedule, scheduleId, isOpen = true, onUpdate, onDelete }: UseScheduleWebSocketOptions) => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); useEffect(() => { if (!schedule || !isOpen) { return; } const handleScheduleEvent = (cloudEvent: any) => { const schedulePayload: Schedule = cloudEvent.data; const eventType = cloudEvent.type; const targetId = scheduleId || schedule.id; if (schedulePayload.id === targetId) { switch (eventType) { case 'com.akashichealthrecords.fhir.schedule.updated': onUpdate(schedulePayload); break; case 'com.akashichealthrecords.fhir.schedule.deleted': onDelete(); break; } } }; subscribe('com.akashichealthrecords.fhir.schedule.updated', handleScheduleEvent); subscribe('com.akashichealthrecords.fhir.schedule.deleted', handleScheduleEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.schedule.updated', handleScheduleEvent); unsubscribe('com.akashichealthrecords.fhir.schedule.deleted', handleScheduleEvent); }; }, [schedule, scheduleId, isOpen, onUpdate, onDelete, subscribe, unsubscribe]); };