const Redis = require('ioredis');

const redis = new Redis({
    host: process.env.REDIS_HOST,
    port: parseInt(process.env.REDIS_PORT),
    password: process.env.REDIS_PASSWORD,
    maxRetriesPerRequest: 3,
    lazyConnect: true,
    retryStrategy(times) {
        const delay = Math.min(times * 50, 2000);
        return delay;
    }
})

redis.on('error', (error) => {
    console.error('redis error', error);
})

redis.on('connect', () => {})
redis.on('reconnecting', () => {
    console.log('reconnecting to redis')
})

async function configure() {
    try {
        await redis.connect();
        await redis.ping();
    } catch (err) {
        console.error('Redis error', err);
    }
}

function connected() {
    return redis.status === 'ready';
}

async function checkRedis() {
    try {
        if (redis.status !== 'ready') {
            await redis.connect().catch(() => {});
        }
        await redis.ping();
        return true;
    } catch (err) {
        return false;
    }
}
    
module.exports = { redis, configure, connected, checkRedis };