import { useEffect, useState, useCallback } from 'react'; import { useQuestionnaireServiceContext } from '../services'; import { describeFetchFailure } from '../utils/fetchFailureMessage'; interface UseFhirQuestionnairesOptions { autoLoad?: boolean; errorMessage?: string; forceReload?: boolean; pageSize?: number; } interface UseFhirQuestionnairesReturn { loading: boolean; error: string | undefined; loadQuestionnaires: () => Promise; clearError: () => void; questionnaireBundle: ReturnType['questionnaireBundle']; questionnaireList: ReturnType['questionnaireList']; } export const useFhirQuestionnaires = (options: UseFhirQuestionnairesOptions = {}): UseFhirQuestionnairesReturn => { const { autoLoad = true, errorMessage = "Failed to load questionnaires", forceReload = false, pageSize = 100 } = options; const { fetchQuestionnairesWithPolling, questionnaireBundle, questionnaireList, shouldReload } = useQuestionnaireServiceContext(); const [loading, setLoading] = useState(false); const [error, setError] = useState(); const loadQuestionnaires = useCallback(async () => { setLoading(true); setError(undefined); try { await fetchQuestionnairesWithPolling(pageSize); } catch (err) { console.error('Failed to load questionnaires:', err); setError(describeFetchFailure(err, errorMessage)); } finally { setLoading(false); } }, [fetchQuestionnairesWithPolling, pageSize, errorMessage]); const clearError = useCallback(() => { setError(undefined); }, []); useEffect(() => { if (!autoLoad) return; // A write elsewhere marks the cached list stale; mounting on it would hand out the old copy. if (!questionnaireBundle || forceReload || shouldReload) { loadQuestionnaires(); } }, [autoLoad, questionnaireBundle, forceReload, shouldReload, loadQuestionnaires]); return { loading, error, loadQuestionnaires, clearError, questionnaireBundle, questionnaireList }; };