"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.REDIS_DEFAULTS = void 0;
exports.getRedisClient = getRedisClient;
exports.closeRedis = closeRedis;
exports.parseRedisTtl = parseRedisTtl;
const redis_1 = require("redis");
const duration_1 = require("../lib/duration");
const logger_1 = require("../lib/logger");
const log = (0, logger_1.createLogger)('redis');
exports.REDIS_DEFAULTS = {
    enabled: false,
    url: 'redis://localhost:6379',
    prefix: 'mgm:',
    embeddingCacheTtl: '30d',
};
let _client = null;
/**
 * Get or create a shared Redis client. Returns null if not configured.
 */
async function getRedisClient(config) {
    if (_client)
        return _client;
    const client = (0, redis_1.createClient)({ url: config.url });
    client.on('error', (err) => {
        log.error({ err }, 'Error');
    });
    client.on('reconnecting', () => {
        log.warn('Reconnecting');
    });
    await client.connect();
    log.info({ url: config.url }, 'Connected');
    _client = client;
    return client;
}
/**
 * Close the shared Redis client.
 */
async function closeRedis() {
    if (_client) {
        await _client.quit();
        _client = null;
        log.info('Connection closed');
    }
}
/**
 * Parse TTL string to seconds (reuse logic from jwt.ts parseTtl).
 * Returns 0 for "0" meaning no TTL.
 */
function parseRedisTtl(ttl) {
    if (ttl === '0')
        return 0;
    return (0, duration_1.parseDuration)(ttl);
}
