import { prisma } from "@/lib/db";

const cache = new Map<string, { value: string | null; expiresAt: number }>();
const TTL = 30_000;

/**
 * Read a value from the Setting table with a 30s in-memory cache.
 * Used by hot paths (RSS, robots, sitemap, header) where roundtripping
 * to Postgres for every request would be wasteful.
 */
export async function settingValue(key: string): Promise<string | null> {
  const now = Date.now();
  const hit = cache.get(key);
  if (hit && hit.expiresAt > now) return hit.value;
  const row = await prisma.setting.findUnique({
    where: { key },
    select: { value: true },
  });
  const value = row?.value ?? null;
  cache.set(key, { value, expiresAt: now + TTL });
  return value;
}
