import { useEffect } from "react"; import { useHistoryStore, type HistoryItem } from "../store/useAppStore"; import { API_BASE } from "../api/client"; export async function saveSessionToBackend( userId: string, item: HistoryItem, ): Promise { try { await fetch(`${API_BASE}/api/sessions/${userId}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(item), }); } catch { // fallback silencioso — localStorage es la fuente de verdad local } } export async function deleteSessionFromBackend( userId: string, filename: string, ): Promise { try { await fetch( `${API_BASE}/api/sessions/${userId}/${encodeURIComponent(filename)}`, { method: "DELETE" }, ); } catch { // fallback silencioso } } export function useLoadSessionHistory(): void { const userId = useHistoryStore((s) => s.userId); const localHistory = useHistoryStore((s) => s.sessionHistory); const setSessionHistory = useHistoryStore((s) => s.setSessionHistory); useEffect(() => { async function load() { try { const res = await fetch(`${API_BASE}/api/sessions/${userId}`); if (!res.ok) return; const data = await res.json(); const remote: HistoryItem[] = data.items ?? []; if (remote.length === 0) return; // Merge remoto + local: dedupe por filename, más reciente gana const merged = [...remote, ...localHistory]; const seen = new Set(); const deduped = merged.filter((item) => { if (seen.has(item.filename)) return false; seen.add(item.filename); return true; }); deduped.sort((a, b) => b.uploadedAt - a.uploadedAt); setSessionHistory(deduped.slice(0, 10)); } catch { // red no disponible — se mantiene historial local } } load(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [userId]); }