import {useState} from 'react'; import {useNavigate} from 'react-router-dom'; import {useTranslation} from 'react-i18next'; import {toast} from 'sonner'; import useSessionExpired from './useSessionExpired.js'; import {apiFetch} from '../utils/api.js'; import {hasSession} from '../utils/auth.js'; const RELOAD_DELAY_MS = 4000; /** * Starts a library sync (POST /api/library/sync), reports the result as a toast and calls * onStarted after a short delay, so the caller can reload once Steam data has arrived. */ export default function useForceSync(onStarted) { const {t} = useTranslation(); const navigate = useNavigate(); const expireSession = useSessionExpired(); const [busy, setBusy] = useState(false); const trigger = async () => { if (!hasSession()) { navigate('/login'); return; } setBusy(true); try { const response = await apiFetch(`${import.meta.env.VITE_CORE_API_URL}/api/library/sync`, { method: 'POST', }); if (response.status === 401) { expireSession(); return; } if (response.status === 429) { const json = await response.json().catch(() => ({})); toast.warning(t('LIBRARY.SYNC_COOLDOWN', {seconds: json.retryAfterSeconds ?? 60})); return; } if (!response.ok) { toast.error(t('LIBRARY.SYNC_FAILED')); return; } toast.success(t('LIBRARY.SYNC_STARTED')); setTimeout(onStarted, RELOAD_DELAY_MS); } catch (err) { console.error('sync trigger error:', err); toast.error(t('INFO.ERROR.NETWORK_FAILURE')); } finally { setBusy(false); } }; return {trigger, busy}; }