// Lightweight in-process TTL cache with prefix-based invalidation.
// Single-process only — suitable for this single-container deployment.

const DEFAULT_TTL_MS = 10 * 60 * 1000; // 10 minutes

const store = new Map(); // key → { value, expiresAt }

function set(key, value, ttlMs = DEFAULT_TTL_MS) {
  store.set(key, { value, expiresAt: Date.now() + ttlMs });
}

function get(key) {
  const entry = store.get(key);
  if (!entry) return undefined;
  if (Date.now() > entry.expiresAt) {
    store.delete(key);
    return undefined;
  }
  return entry.value;
}

function del(key) {
  store.delete(key);
}

// Remove all keys that start with prefix — used to invalidate a whole experiment's worth of cached data.
function delByPrefix(prefix) {
  for (const key of store.keys()) {
    if (key.startsWith(prefix)) store.delete(key);
  }
}

module.exports = { set, get, del, delByPrefix };
