import { useEffect, useState, useCallback } from 'react'; import { usePatientServiceContext, useCoverageServiceContext } from '../services'; import { describeFetchFailure } from '../utils/fetchFailureMessage'; import { patientCacheGuard } from '../utils/cacheOwner'; export const useFhirCoverages = ({ autoLoad = true, errorMessage = 'Failed to load insurance' } = {}) => { const { patientState } = usePatientServiceContext(); const { fetchCoveragesWithPolling, coveragesBundle, coverageList, cachedForPatientId } = useCoverageServiceContext(); const [loading, setLoading] = useState(false); const [error, setError] = useState(); const loadCoverages = useCallback(async () => { if (!patientState) return; setLoading(true); setError(undefined); try { await fetchCoveragesWithPolling(patientState); } catch (err) { console.error('Failed to load insurance:', err); setError(describeFetchFailure(err, errorMessage)); } finally { setLoading(false); } }, [patientState, fetchCoveragesWithPolling, errorMessage]); useEffect(() => { if (!autoLoad || !patientState) return; if (!coveragesBundle || cachedForPatientId !== patientState.id) loadCoverages(); }, [autoLoad, patientState, coveragesBundle, cachedForPatientId, loadCoverages]); // The cache is shared across patients: hand it out only when it holds the patient asked about. const guard = patientCacheGuard(cachedForPatientId, patientState?.id); return { loading: guard.loading(loading, Boolean(error)), error, attempted: Boolean(patientState), loadCoverages, coveragesBundle: guard.owned ? coveragesBundle : undefined, coverageList: guard.list(coverageList), }; };