import type { EngineResponse } from "./engines/shared";

const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes

interface CacheEntry {
  value: EngineResponse;
  expiresAt: number;
}

const cache = new Map<string, CacheEntry>();

function cacheKey(engine: string, query: string): string {
  return `${engine}::${query}`;
}

export function getCached(engine: string, query: string): EngineResponse | null {
  const key = cacheKey(engine, query);
  const entry = cache.get(key);
  if (!entry || Date.now() > entry.expiresAt) {
    cache.delete(key);
    return null;
  }
  return entry.value;
}

export function setCached(engine: string, query: string, value: EngineResponse): void {
  cache.set(cacheKey(engine, query), { value, expiresAt: Date.now() + CACHE_TTL_MS });
}

export async function getCachedOrQuery(
  engine: string,
  query: string,
  queryFn: () => Promise<EngineResponse>,
): Promise<EngineResponse> {
  const cached = getCached(engine, query);
  if (cached) return cached;
  const result = await queryFn();
  setCached(engine, query, result);
  return result;
}
