import { useEffect } from 'react'; import { DetectedIssue } from 'fhir/r4'; import { usePatientServiceContext, useWebSocketServiceContext } from '../services'; interface UseDetectedIssueWebSocketOptions { detectedIssue?: DetectedIssue; detectedIssueId?: string; isOpen?: boolean; onUpdate: (detectedIssue: DetectedIssue) => void; onDelete: () => void; } export const useFhirDetectedIssueTargetedBroadcast = ({ detectedIssue, detectedIssueId, isOpen = true, onUpdate, onDelete }: UseDetectedIssueWebSocketOptions) => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); const { patientState } = usePatientServiceContext(); useEffect(() => { if (!patientState || !detectedIssue || !isOpen) { return; } const handleDetectedIssueEvent = (cloudEvent: any) => { const detectedIssuePayload: DetectedIssue = cloudEvent.data; const eventType = cloudEvent.type; const targetId = detectedIssueId || detectedIssue.id; if (detectedIssuePayload.id === targetId) { switch (eventType) { case 'com.akashichealthrecords.fhir.detectedissue.updated': onUpdate(detectedIssuePayload); break; case 'com.akashichealthrecords.fhir.detectedissue.deleted': onDelete(); break; } } }; subscribe('com.akashichealthrecords.fhir.detectedissue.updated', handleDetectedIssueEvent); subscribe('com.akashichealthrecords.fhir.detectedissue.deleted', handleDetectedIssueEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.detectedissue.updated', handleDetectedIssueEvent); unsubscribe('com.akashichealthrecords.fhir.detectedissue.deleted', handleDetectedIssueEvent); }; }, [patientState, detectedIssue, detectedIssueId, isOpen, onUpdate, onDelete, subscribe, unsubscribe]); };