import { useEffect, useState, useCallback } from 'react'; import { Organization } from 'fhir/r4'; import { useAuthServiceContext, useHealthcareServiceServiceContext } from '../services'; import { describeFetchFailure } from '../utils/fetchFailureMessage'; import { usePracticeUnlocked } from '../utils/practiceUnlocked'; interface UseFhirHealthcareServicesOptions { autoLoad?: boolean; errorMessage?: string; forceReload?: boolean; } interface UseFhirHealthcareServicesReturn { loading: boolean; error: string | undefined; loadHealthcareServices: (force?: boolean) => Promise; clearError: () => void; healthcareServicesBundle: ReturnType['healthcareServicesBundle']; healthcareServicesList: ReturnType['healthcareServicesList']; } export const useFhirHealthcareServices = (options: UseFhirHealthcareServicesOptions = {}): UseFhirHealthcareServicesReturn => { const { autoLoad = true, errorMessage = "Failed to load healthcare services", forceReload = false } = options; const { wpOrganization } = useAuthServiceContext(); const { fetchHealthcareServicesWithPolling, healthcareServicesBundle, healthcareServicesList } = useHealthcareServiceServiceContext(); const [loading, setLoading] = useState(false); const [error, setError] = useState(); const loadHealthcareServices = useCallback(async (force = false) => { if (!wpOrganization.current) { setError('Organization not available'); return; } setLoading(true); setError(undefined); try { await fetchHealthcareServicesWithPolling(wpOrganization.current as Organization, force); } catch (err) { console.error('Failed to load healthcare services:', err); setError(describeFetchFailure(err, errorMessage)); } finally { setLoading(false); } }, [wpOrganization, fetchHealthcareServicesWithPolling, errorMessage]); // A read refused while the practice waited for its owner is asked again once it is unlocked. usePracticeUnlocked(() => { if (error) void loadHealthcareServices(true); }); const clearError = useCallback(() => { setError(undefined); }, []); useEffect(() => { if (!autoLoad) return; if (!wpOrganization.current) return; if (!healthcareServicesBundle || forceReload) { loadHealthcareServices(); } }, [autoLoad, wpOrganization, healthcareServicesBundle, forceReload, loadHealthcareServices]); return { loading, error, loadHealthcareServices, clearError, healthcareServicesBundle, healthcareServicesList }; };