import type { CacheStore } from "./redis-cache";

type Entry = { value: string; expiresAt: number };

export function createMemoryCache(defaultTtlSeconds: number): CacheStore {
  const store = new Map<string, Entry>();

  function nowMs() {
    return Date.now();
  }

  function isExpired(e: Entry) {
    return e.expiresAt !== 0 && nowMs() > e.expiresAt;
  }

  return {
    async getJson<T>(key: string) {
      const e = store.get(key);
      if (!e) return undefined;
      if (isExpired(e)) {
        store.delete(key);
        return undefined;
      }
      try {
        return JSON.parse(e.value) as T;
      } catch {
        store.delete(key);
        return undefined;
      }
    },

    async setJson(key: string, value: unknown, ttlSeconds?: number) {
      const ttl = Math.max(1, Math.floor(ttlSeconds ?? defaultTtlSeconds));
      store.set(key, {
        value: JSON.stringify(value),
        expiresAt: nowMs() + ttl * 1000,
      });
    },

    async flush() {
      store.clear();
    },

    async close() {
      // no-op
    },
  };
}

