"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createRedisOptions = createRedisOptions;
exports.createRedis = createRedis;
exports.disconnectAllRedis = disconnectAllRedis;
const tslib_1 = require("tslib");
function __assignType(fn, args) {
    fn.__type = args;
    return fn;
}
const ioredis_1 = tslib_1.__importDefault(require("ioredis"));
const resolver_1 = require("../../app/resolver");
const package_1 = require("../io/package");
function createRedisOptions(configPrefix) {
    const config = { ...(0, resolver_1.getAppConfig)() };
    if (configPrefix) {
        for (const key in config) {
            if (key.startsWith(`${configPrefix}_REDIS_`)) {
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                config[key.substring(configPrefix.length + 1)] = config[key];
            }
        }
    }
    const prefix = config.REDIS_PREFIX ?? (0, package_1.getPackageName)() ?? 'app';
    if (config.REDIS_SENTINEL_HOST) {
        const options = {
            sentinels: [
                {
                    host: config.REDIS_SENTINEL_HOST,
                    port: config.REDIS_SENTINEL_PORT
                }
            ],
            name: config.REDIS_SENTINEL_NAME
        };
        return { options, prefix };
    }
    if (config.REDIS_HOST) {
        const options = { host: config.REDIS_HOST, port: config.REDIS_PORT };
        return { options, prefix };
    }
    throw new Error('REDIS_HOST or REDIS_SENTINEL_HOST must be configured');
}
createRedisOptions.__type = ['configPrefix', 'RedisOptions', 'options', 'prefix', 'createRedisOptions', 'P&2!8P"w"4#&4$M/%'];
const allClients = (Set.Ω = [['!']], new Set());
function createRedis(configPrefix) {
    const { options, prefix } = createRedisOptions(configPrefix);
    const client = new ioredis_1.default(options);
    allClients.add(client);
    client.on('end', () => allClients.delete(client));
    return { client, prefix };
}
createRedis.__type = ['configPrefix', 'client', 'prefix', 'createRedis', 'P&2!8P!4"&4#M/$'];
async function disconnectAllRedis() {
    const clients = [...allClients];
    allClients.clear();
    await Promise.all(clients.map(__assignType(c => c.quit().catch(() => { }), ['c', '', 'P"2!"/"'])));
}
disconnectAllRedis.__type = ['disconnectAllRedis', 'P$`/!'];
//# sourceMappingURL=redis.js.map