import { useEffect } from 'react'; import { EpisodeOfCare } from 'fhir/r4'; import { usePatientServiceContext, useWebSocketServiceContext } from '../services'; interface UseEpisodeOfCareWebSocketOptions { episodeOfCare?: EpisodeOfCare; episodeOfCareId?: string; isOpen?: boolean; onUpdate: (episodeOfCare: EpisodeOfCare) => void; onDelete: () => void; } export const useFhirEpisodeOfCareTargetedBroadcast = ({ episodeOfCare, episodeOfCareId, isOpen = true, onUpdate, onDelete }: UseEpisodeOfCareWebSocketOptions) => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); const { patientState } = usePatientServiceContext(); useEffect(() => { if (!patientState || !episodeOfCare || !isOpen) { return; } const handleEpisodeOfCareEvent = (cloudEvent: any) => { const episodeOfCarePayload: EpisodeOfCare = cloudEvent.data; const eventType = cloudEvent.type; const targetId = episodeOfCareId || episodeOfCare.id; if (episodeOfCarePayload.id === targetId) { switch (eventType) { case 'com.akashichealthrecords.fhir.episodeofcare.updated': onUpdate(episodeOfCarePayload); break; case 'com.akashichealthrecords.fhir.episodeofcare.deleted': onDelete(); break; } } }; subscribe('com.akashichealthrecords.fhir.episodeofcare.updated', handleEpisodeOfCareEvent); subscribe('com.akashichealthrecords.fhir.episodeofcare.deleted', handleEpisodeOfCareEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.episodeofcare.updated', handleEpisodeOfCareEvent); unsubscribe('com.akashichealthrecords.fhir.episodeofcare.deleted', handleEpisodeOfCareEvent); }; }, [patientState, episodeOfCare, episodeOfCareId, isOpen, onUpdate, onDelete, subscribe, unsubscribe]); };