import { Attachment } from '../types'; export type DownloadEntry = { attachment: Attachment; courseId: string; courseTitle: string; downloadedAt: string }; const keyFor = (userId: string) => `ca-downloads:${userId}`; export const readDownloads = (userId?: string): DownloadEntry[] => { if (!userId) return []; try { const value = JSON.parse(localStorage.getItem(keyFor(userId)) || '[]'); return Array.isArray(value) ? value : []; } catch { return []; } }; export const recordDownload = (userId: string, attachment: Attachment, courseId: string, courseTitle: string) => { const entry: DownloadEntry = { attachment, courseId, courseTitle, downloadedAt: new Date().toISOString() }; const next = [entry, ...readDownloads(userId).filter((item) => item.attachment.id !== attachment.id)].slice(0, 100); try { localStorage.setItem(keyFor(userId), JSON.stringify(next)); window.dispatchEvent(new Event('ca-downloads')); } catch { /* A completed download does not depend on local history. */ } };