const redis = require('redis');
require('dotenv').config();

// 创建Redis客户端
const createRedisClient = () => {
  const client = redis.createClient({
    socket: {
      host: process.env.REDIS_HOST || 'localhost',
      port: process.env.REDIS_PORT || 6379
    },
    password: process.env.REDIS_PASSWORD || '',
    legacyMode: false
  });

  // 错误处理
  client.on('error', (err) => {
    console.error('❌ Redis连接错误:', err);
  });

  // 连接成功
  client.on('connect', () => {
    console.log('✅ Redis连接成功');
  });

  return client;
};

// 创建并连接Redis客户端
const redisClient = createRedisClient();

// 连接Redis
const connectRedis = async () => {
  try {
    await redisClient.connect();
    return true;
  } catch (error) {
    console.error('❌ Redis连接失败:', error.message);
    return false;
  }
};

module.exports = { redisClient, connectRedis };