import type { RequestHandler } from 'express';

/** Public GETs are cacheable for 5 minutes (Express adds weak ETags automatically). */
export const publicCache: RequestHandler = (req, res, next) => {
  if (req.method === 'GET') res.set('Cache-Control', 'public, max-age=300');
  next();
};

/** Admin responses must never be cached by browsers or proxies. */
export const noStore: RequestHandler = (_req, res, next) => {
  res.set('Cache-Control', 'no-store');
  next();
};

/**
 * Tiny in-memory LRU for hot public GETs (search suggest, detail pages). ~5 min TTL, bounded size
 * so it stays small on shared hosting. Keyed by full URL. Call `clearMemoryCache()` after admin writes.
 */
const store = new Map<string, { at: number; body: unknown }>();
const TTL = 5 * 60_000;
const MAX = 500;

const clearHooks: (() => void)[] = [];
/** Other caches (e.g. rendered website pages) register here so admin writes clear them too. */
export const onCacheClear = (fn: () => void) => clearHooks.push(fn);
export const clearMemoryCache = () => {
  store.clear();
  for (const fn of clearHooks) fn();
};

export const memoryCache: RequestHandler = (req, res, next) => {
  if (req.method !== 'GET' || process.env.NODE_ENV === 'test') return next();
  const key = req.originalUrl;
  const hit = store.get(key);
  if (hit && Date.now() - hit.at < TTL) {
    store.delete(key);
    store.set(key, hit); // refresh LRU position
    res.set('X-Cache', 'HIT');
    res.json(hit.body);
    return;
  }
  const json = res.json.bind(res);
  res.json = (body: unknown) => {
    if (res.statusCode === 200) {
      store.set(key, { at: Date.now(), body });
      if (store.size > MAX) store.delete(store.keys().next().value as string);
    }
    res.set('X-Cache', 'MISS');
    return json(body);
  };
  next();
};
