import { useEffect } from 'react'; import { Task } from 'fhir/r4'; import { usePatientServiceContext, useWebSocketServiceContext } from '../services'; interface UseTaskWebSocketOptions { task?: Task; taskId?: string; isOpen?: boolean; onUpdate: (task: Task) => void; onDelete: () => void; } export const useFhirTaskTargetedBroadcast = ({ task, taskId, isOpen = true, onUpdate, onDelete }: UseTaskWebSocketOptions) => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); const { patientState } = usePatientServiceContext(); useEffect(() => { if (!patientState || !task || !isOpen) { return; } const handleTaskEvent = (cloudEvent: any) => { const taskPayload: Task = cloudEvent.data; const eventType = cloudEvent.type; const targetId = taskId || task.id; if (taskPayload.id === targetId) { switch (eventType) { case 'com.akashichealthrecords.fhir.task.updated': onUpdate(taskPayload); break; case 'com.akashichealthrecords.fhir.task.deleted': onDelete(); break; } } }; subscribe('com.akashichealthrecords.fhir.task.updated', handleTaskEvent); subscribe('com.akashichealthrecords.fhir.task.deleted', handleTaskEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.task.updated', handleTaskEvent); unsubscribe('com.akashichealthrecords.fhir.task.deleted', handleTaskEvent); }; }, [patientState, task, taskId, isOpen, onUpdate, onDelete, subscribe, unsubscribe]); };