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