import type { AuthUser, Product } from "@/lib/types"; /** * The last confirmed session and catalogue, so the terminal can start and * keep selling with no network. Only a snapshot for display and for * labelling queued sales: the server still authenticates every sync with * the httpOnly cookies and re-prices every line. */ const KEY = "aquaflow_terminal_session"; /** The branch's stock as the server last reported it. */ export interface StockSnapshot { byProduct: Record; fetchedAt: string; } export interface SessionSnapshot { user: AuthUser; features: { mpesa: boolean }; products: Product[]; stock?: StockSnapshot; savedAt: string; } export function loadSession(): SessionSnapshot | null { try { const raw = localStorage.getItem(KEY); return raw ? (JSON.parse(raw) as SessionSnapshot) : null; } catch { return null; } } export function saveSession(update: Partial & { user: AuthUser }): void { try { const prev = loadSession(); const sameUser = prev?.user.id === update.user.id; const next: SessionSnapshot = { features: update.features ?? (sameUser ? prev!.features : { mpesa: false }), products: update.products ?? (sameUser ? prev!.products : []), stock: update.stock ?? (sameUser ? prev!.stock : undefined), user: update.user, savedAt: new Date().toISOString(), }; localStorage.setItem(KEY, JSON.stringify(next)); } catch { // Storage full or blocked: the terminal still works online. } } export function clearSession(): void { try { localStorage.removeItem(KEY); } catch { // ignore } }