import { useEffect } from 'react'; import { CarePlan } from 'fhir/r4'; import { usePatientServiceContext, useWebSocketServiceContext } from '../services'; interface UseCarePlanWebSocketOptions { carePlan?: CarePlan; carePlanId?: string; isOpen?: boolean; onUpdate: (carePlan: CarePlan) => void; onDelete: () => void; } export const useFhirCarePlanTargetedBroadcast = ({ carePlan, carePlanId, isOpen = true, onUpdate, onDelete }: UseCarePlanWebSocketOptions) => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); const { patientState } = usePatientServiceContext(); useEffect(() => { if (!patientState || !carePlan || !isOpen) { return; } const handleCarePlanEvent = (cloudEvent: any) => { const carePlanPayload: CarePlan = cloudEvent.data; const eventType = cloudEvent.type; const targetId = carePlanId || carePlan.id; if (carePlanPayload.id === targetId) { switch (eventType) { case 'com.akashichealthrecords.fhir.careplan.updated': onUpdate(carePlanPayload); break; case 'com.akashichealthrecords.fhir.careplan.deleted': onDelete(); break; } } }; subscribe('com.akashichealthrecords.fhir.careplan.updated', handleCarePlanEvent); subscribe('com.akashichealthrecords.fhir.careplan.deleted', handleCarePlanEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.careplan.updated', handleCarePlanEvent); unsubscribe('com.akashichealthrecords.fhir.careplan.deleted', handleCarePlanEvent); }; }, [patientState, carePlan, carePlanId, isOpen, onUpdate, onDelete, subscribe, unsubscribe]); };