"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.cacheGet = cacheGet;
exports.cacheSet = cacheSet;
exports.cacheClear = cacheClear;
exports.getCacheStats = getCacheStats;
exports.cachedQuery = cachedQuery;
exports.cachedGet = cachedGet;
exports.invalidateOnWrite = invalidateOnWrite;
const database_1 = require("../database/database");
const cache = new Map();
const MAX_CACHE_SIZE = 500;
const DEFAULT_TTL_MS = 5000;
let hits = 0;
let misses = 0;
function cacheGet(key) {
    const entry = cache.get(key);
    if (!entry) {
        misses++;
        return undefined;
    }
    if (Date.now() > entry.expiresAt) {
        cache.delete(key);
        misses++;
        return undefined;
    }
    hits++;
    return entry.data;
}
function cacheSet(key, data, ttlMs = DEFAULT_TTL_MS) {
    if (cache.size >= MAX_CACHE_SIZE) {
        const oldest = cache.entries().next();
        if (oldest.value)
            cache.delete(oldest.value[0]);
    }
    cache.set(key, { data, expiresAt: Date.now() + ttlMs });
}
function cacheClear(pattern) {
    if (!pattern) {
        cache.clear();
        return;
    }
    for (const key of cache.keys()) {
        if (key.includes(pattern))
            cache.delete(key);
    }
}
function getCacheStats() {
    const total = hits + misses;
    return {
        size: cache.size,
        hits,
        misses,
        hitRate: total > 0 ? `${((hits / total) * 100).toFixed(1)}%` : '0%',
    };
}
function cachedQuery(cacheKey, sql, params = [], ttlMs = DEFAULT_TTL_MS) {
    const cached = cacheGet(cacheKey);
    if (cached !== undefined)
        return cached;
    const db = (0, database_1.getDb)();
    const result = db.prepare(sql).all(...params);
    cacheSet(cacheKey, result, ttlMs);
    return result;
}
function cachedGet(cacheKey, sql, params = [], ttlMs = DEFAULT_TTL_MS) {
    const cached = cacheGet(cacheKey);
    if (cached !== undefined)
        return cached;
    const db = (0, database_1.getDb)();
    const result = db.prepare(sql).get(...params);
    if (result !== undefined)
        cacheSet(cacheKey, result, ttlMs);
    return result;
}
function invalidateOnWrite(patterns) {
    for (const p of patterns)
        cacheClear(p);
}
//# sourceMappingURL=query-cache.js.map