import IORedis from 'ioredis';
import { env, createLogger } from '@4runr/shared';
const logger = createLogger('Gateway:Redis');
let redisClient = null;
let redisPromise = null;
export async function getRedisClient() {
    if (redisClient) {
        return redisClient;
    }
    if (redisPromise) {
        return await redisPromise;
    }
    redisPromise = (async () => {
        const redisUrl = env.REDIS_URL || process.env['REDIS_URL'];
        if (!redisUrl) {
            return null;
        }
        try {
            const client = new IORedis(redisUrl, {
                maxRetriesPerRequest: 3,
                lazyConnect: true,
                retryStrategy: (times) => {
                    if (times > 3) {
                        return null;
                    }
                    return Math.min(times * 200, 2000);
                },
            });
            client.on('error', (error) => {
                logger.warn('Redis connection error', { error: error.message });
            });
            client.on('connect', () => {
                logger.info('Redis connected successfully');
            });
            await client.connect();
            redisClient = client;
            return client;
        }
        catch (error) {
            logger.warn('Redis connection failed', {
                error: error instanceof Error ? error.message : String(error),
                fallback: 'in-memory idempotency store'
            });
            return null;
        }
    })();
    return await redisPromise;
}
export async function disconnectRedis() {
    if (redisClient) {
        await redisClient.quit();
        redisClient = null;
        redisPromise = null;
    }
}
export async function isRedisAvailable() {
    const client = await getRedisClient();
    if (!client) {
        return false;
    }
    try {
        await client.ping();
        return true;
    }
    catch {
        return false;
    }
}
//# sourceMappingURL=redis.js.map