"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.__tsfTypeAliases = void 0;
exports.createRedisOptions = createRedisOptions;
exports.createRedis = createRedis;
exports.disconnectAllRedis = disconnectAllRedis;
const tslib_1 = require("tslib");
const _a = tslib_1.__importStar(require("@zyno-io/ts-server-foundation/type-metadata-runtime"));
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 of Object.keys(config)) {
            if (key.startsWith(`${configPrefix}_REDIS_`)) {
                if (config[key] === undefined)
                    continue;
                config[key.substring(configPrefix.length + 1)] = config[key];
            }
        }
    }
    const prefix = String(config.REDIS_PREFIX ?? (0, package_1.getPackageName)() ?? 'app');
    if (config.REDIS_SENTINEL_HOST) {
        return {
            prefix,
            options: {
                sentinels: [
                    {
                        host: String(config.REDIS_SENTINEL_HOST),
                        port: Number(config.REDIS_SENTINEL_PORT ?? 26379)
                    }
                ],
                name: config.REDIS_SENTINEL_NAME ? String(config.REDIS_SENTINEL_NAME) : undefined,
                failoverDetector: true,
                sentinelMaxConnections: 1,
                reconnectOnError: error => (error.message.startsWith('READONLY') ? 2 : false)
            }
        };
    }
    if (config.REDIS_HOST) {
        return {
            prefix,
            options: {
                host: String(config.REDIS_HOST),
                port: Number(config.REDIS_PORT ?? 6379)
            }
        };
    }
    throw new Error('REDIS_HOST or REDIS_SENTINEL_HOST must be configured');
}
const allClients = 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 };
}
async function disconnectAllRedis() {
    const clients = [...allClients];
    allClients.clear();
    await Promise.all(clients.map(client => client.quit().catch(() => { })));
}
exports.__tsfTypeAliases = _a.decodeCompactMetadataV1("[1,{\"RedisConnection\":{\"kind\":18,\"typeName\":\"RedisConnection\",\"types\":[{\"kind\":20,\"name\":\"client\",\"type\":{\"kind\":16,\"typeName\":\"TClient\",\"classType\":{\"$tsf\":0}},\"optional\":false},{\"kind\":20,\"name\":\"prefix\",\"type\":{\"kind\":6},\"optional\":false}]}}]", [() => (typeof TClient !== "undefined" ? TClient : (typeof exports !== "undefined" ? exports.TClient : undefined))]);
//# sourceMappingURL=redis.js.map