type CacheEntry<T> = {
  data: T;
  expiry: number;
};

const globalForCache = globalThis as unknown as {
  __memoryCacheStore?: Map<string, CacheEntry<any>>;
};

const store = globalForCache.__memoryCacheStore ?? new Map<string, CacheEntry<any>>();
globalForCache.__memoryCacheStore = store;

export function getCached<T>(key: string): T | null {
  const entry = store.get(key);
  if (!entry) return null;
  if (Date.now() > entry.expiry) {
    store.delete(key);
    return null;
  }
  return entry.data;
}

export function setCached<T>(key: string, data: T, ttlMs: number = 15000): void {
  store.set(key, {
    data,
    expiry: Date.now() + ttlMs,
  });
}

export function clearCache(prefix?: string): void {
  if (!prefix) {
    store.clear();
    return;
  }
  for (const key of store.keys()) {
    if (key.startsWith(prefix)) {
      store.delete(key);
    }
  }
}
