/**
 * Redis Cache Module
 * Handles Redis connection and caching operations
 */

const { createClient } = require('redis');

let redisClient = null;

async function connectRedis() {
    redisClient = createClient({ url: process.env.REDIS_URL });
    redisClient.on('error', (err) => console.error('Redis Error:', err));
    await redisClient.connect();
    return redisClient;
}

function getRedisClient() {
    return redisClient;
}

async function cacheGet(key) {
    if (!redisClient) return null;
    const data = await redisClient.get(key);
    return data ? JSON.parse(data) : null;
}

async function cacheSet(key, value, expirySeconds = 3600) {
    if (!redisClient) return false;
    await redisClient.setEx(key, expirySeconds, JSON.stringify(value));
    return true;
}

async function cacheDelete(key) {
    if (!redisClient) return false;
    await redisClient.del(key);
    return true;
}

module.exports = { connectRedis, getRedisClient, cacheGet, cacheSet, cacheDelete };
