import { useEffect } from 'react'; import { AllergyIntolerance } from 'fhir/r4'; import { usePatientServiceContext, useWebSocketServiceContext } from '../services'; interface UseAllergyIntoleranceWebSocketOptions { allergyIntolerance?: AllergyIntolerance; allergyIntoleranceId?: string; isOpen?: boolean; onUpdate: (allergyIntolerance: AllergyIntolerance) => void; onDelete: () => void; } export const useFhirAllergyIntoleranceTargetedBroadcast = ({ allergyIntolerance, allergyIntoleranceId, isOpen = true, onUpdate, onDelete }: UseAllergyIntoleranceWebSocketOptions) => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); const { patientState } = usePatientServiceContext(); useEffect(() => { if (!patientState || !allergyIntolerance || !isOpen) { return; } const handleAllergyIntoleranceEvent = (cloudEvent: any) => { const allergyIntolerancePayload: AllergyIntolerance = cloudEvent.data; const eventType = cloudEvent.type; const targetId = allergyIntoleranceId || allergyIntolerance.id; if (allergyIntolerancePayload.id === targetId) { switch (eventType) { case 'com.akashichealthrecords.fhir.allergyintolerance.updated': onUpdate(allergyIntolerancePayload); break; case 'com.akashichealthrecords.fhir.allergyintolerance.deleted': onDelete(); break; } } }; subscribe('com.akashichealthrecords.fhir.allergyintolerance.updated', handleAllergyIntoleranceEvent); subscribe('com.akashichealthrecords.fhir.allergyintolerance.deleted', handleAllergyIntoleranceEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.allergyintolerance.updated', handleAllergyIntoleranceEvent); unsubscribe('com.akashichealthrecords.fhir.allergyintolerance.deleted', handleAllergyIntoleranceEvent); }; }, [patientState, allergyIntolerance, allergyIntoleranceId, isOpen, onUpdate, onDelete, subscribe, unsubscribe]); };