/**
 * In-process LRU cache for flight_search results.
 *
 * Keyed by sha1 of the normalized query. Map's insertion-order semantics give
 * us LRU on touch (delete + re-insert). 15-minute TTL prevents stale prices.
 * Capped at 200 entries — well under any agent's working set.
 *
 * Cache hits skip wrapFetch entirely, so they:
 *   - do not write a row to tool_egress
 *   - do not consume rate-limit quota (that gate runs in executeRegistryTool
 *     before the adapter, and we surface cache_hit through the source field)
 */

import { createHash } from 'node:crypto';

const TTL_MS = 15 * 60 * 1000;
const CAPACITY = 200;

const cache = new Map();

export function makeFlightCacheKey(normalized) {
  return createHash('sha1').update(JSON.stringify(normalized)).digest('hex');
}

export function getCached(key) {
  const entry = cache.get(key);
  if (!entry) return null;
  if (Date.now() > entry.expires_at) {
    cache.delete(key);
    return null;
  }
  cache.delete(key);
  cache.set(key, entry);
  return entry.value;
}

export function setCached(key, value) {
  if (cache.has(key)) cache.delete(key);
  cache.set(key, { value, expires_at: Date.now() + TTL_MS });
  while (cache.size > CAPACITY) {
    const oldest = cache.keys().next().value;
    cache.delete(oldest);
  }
}

export function clearFlightCache() {
  cache.clear();
}

export function flightCacheSize() {
  return cache.size;
}
