import { CommunicationRequest, Communication } from 'fhir/r4'; import { useWebSocketServiceContext } from '../services'; import { useEffect } from 'react'; interface UseFhirCommunicationRequestTargetedBroadcastOptions { communicationRequest?: CommunicationRequest; communicationRequestId?: string; threadId?: string; // NEW isOpen?: boolean; onUpdate: (communicationRequest: CommunicationRequest) => void; onDelete: () => void; onMessageUpdate?: (communication: Communication) => void; // NEW } export const useFhirCommunicationRequestTargetedBroadcast = ({ communicationRequest, communicationRequestId, threadId, isOpen = true, onUpdate, onDelete, onMessageUpdate }: UseFhirCommunicationRequestTargetedBroadcastOptions) => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); useEffect(() => { if ((!communicationRequest && !threadId) || !isOpen) { return; } const targetRequestId = communicationRequestId || communicationRequest?.id; const handleCommunicationRequestEvent = (cloudEvent: any) => { const payload: CommunicationRequest = cloudEvent.data; const eventType = cloudEvent.type; if (payload.id === targetRequestId) { switch (eventType) { case 'com.akashichealthrecords.fhir.communicationrequest.updated': onUpdate(payload); break; case 'com.akashichealthrecords.fhir.communicationrequest.deleted': onDelete(); break; } } }; const handleCommunicationEvent = (cloudEvent: any) => { if (!onMessageUpdate) return; const payload: Communication = cloudEvent.data; // thread-first detection const basedOnRef = payload.basedOn?.[0]?.reference; let messageThreadId: string | null = null; if (basedOnRef?.startsWith('Thread/')) { messageThreadId = basedOnRef.split('/')[1]; } else if (basedOnRef && threadId) { // fallback messageThreadId = threadId; } if (messageThreadId && threadId && messageThreadId === threadId) { onMessageUpdate(payload); } }; // legacy subscriptions subscribe('com.akashichealthrecords.fhir.communicationrequest.updated', handleCommunicationRequestEvent); subscribe('com.akashichealthrecords.fhir.communicationrequest.deleted', handleCommunicationRequestEvent); // NEW thread-aware message events subscribe('com.akashichealthrecords.fhir.communication.created', handleCommunicationEvent); subscribe('com.akashichealthrecords.fhir.communication.updated', handleCommunicationEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.communicationrequest.updated', handleCommunicationRequestEvent); unsubscribe('com.akashichealthrecords.fhir.communicationrequest.deleted', handleCommunicationRequestEvent); unsubscribe('com.akashichealthrecords.fhir.communication.created', handleCommunicationEvent); unsubscribe('com.akashichealthrecords.fhir.communication.updated', handleCommunicationEvent); }; }, [ communicationRequest, communicationRequestId, threadId, isOpen, onUpdate, onDelete, onMessageUpdate, subscribe, unsubscribe ]); };