const redis = require('redis');
const config = require('../../config.json');
const Logger = require('../../lib/Logger');
const path = require('path');

class RedisClient {
    constructor() {
        // 创建 Redis 客户端实例
        this.client = redis.createClient({
            host: config.redis.host,
            port: config.redis.port,
            password: config.redis.password || null
        });

        this.logger = new Logger(path.join(__dirname, '../../logs/Redis.log'), 'INFO');

        // 处理连接错误
        this.client.on('error', (err) => {
            this.logger.error(`Redis连接出错：${err.stack}`);
        });

        // 确保连接成功
        this.client.on('connect', () => {
            this.logger.info('Redis连接成功！');
        });

        // 在连接建立时标记为已连接状态
        this.client.on('ready', () => {
            this.logger.info('Redis客户端已就绪！');
        });

        // 在客户端关闭时处理事件
        this.client.on('end', () => {
            this.logger.warn('Redis客户端连接已关闭！');
        });
    }

    // 获取 Redis 客户端实例
    getClient() {
        if (!this.client.isOpen) {
            this.client.connect().catch((err) => {
                this.logger.error(`重新连接Redis时出错：${err.stack}`);
            });
        }
        return this.client;
    }
}

const Redis = new RedisClient().getClient();
module.exports = Redis;
