import type { Ctx } from "./http/route.js";

const store = new Map<string, { at: number; value: Promise<unknown> }>();
/** Keeps a summary page for a few seconds and lets simultaneous visitors share one calculation. The key holds everything that limits what a person may see. */
export function cached<T>(c: Ctx, name: string, build: () => Promise<T>, seconds = 20): Promise<T> {
  const a = c.access, key = JSON.stringify([name, c.pid, a.roleCode, a.providerId, a.siteIds, a.classIds, c.req.query ?? {}]), hit = store.get(key);
  if (hit && Date.now() - hit.at < seconds * 1000) return hit.value as Promise<T>;
  const value = build();
  store.set(key, { at: Date.now(), value });
  value.catch(() => store.delete(key));
  if (store.size > 500) store.delete(store.keys().next().value!);
  return value;
}
