// Prices the user has seen on store pages, kept only in extension storage for 24 hours. import { lineKey, type SeenPrice, type Store } from './model'; export interface KeyValue { get(key: string): Promise; set(key: string, value: unknown): Promise; } const KEY = 'seen-prices'; const TTL_MS = 24 * 3600 * 1000; const MAX_ENTRIES = 2000; const fresh = (p: SeenPrice, now: Date) => now.getTime() - Date.parse(p.seenAt) < TTL_MS; async function load(kv: KeyValue): Promise { const value = await kv.get(KEY); return Array.isArray(value) ? (value as SeenPrice[]) : []; } export async function recordSeen(kv: KeyValue, prices: SeenPrice[], now = new Date()): Promise { const byKey = new Map(); for (const p of [...(await load(kv)), ...prices]) if (fresh(p, now)) byKey.set(p.locationKey + '|' + lineKey(p), p); const kept = [...byKey.values()].sort((a, b) => Date.parse(b.seenAt) - Date.parse(a.seenAt)).slice(0, MAX_ENTRIES); await kv.set(KEY, kept); } /** Seen prices still valid now: under 24 hours old and from each store's current delivery location. */ export async function freshSeen(kv: KeyValue, currentLocation: Partial>, now = new Date()): Promise { return (await load(kv)).filter((p) => fresh(p, now) && currentLocation[p.store] === p.locationKey); }