import Redis from 'ioredis';
import dotenv from 'dotenv';

dotenv.config();

/**
 * Redis Client Singleton
 * Cache és session management-hez
 */
class RedisClient {
  constructor() {
    if (!RedisClient.instance) {
      this.client = new Redis({
        host: process.env.REDIS_HOST || 'localhost',
        port: process.env.REDIS_PORT || 6379,
        retryStrategy: (times) => {
          const delay = Math.min(times * 50, 2000);
          return delay;
        },
      });

      this.client.on('connect', () => {
        console.log('✅ Redis connected');
      });

      this.client.on('error', (err) => {
        console.error('❌ Redis error:', err);
      });

      RedisClient.instance = this;
    }
    return RedisClient.instance;
  }

  getClient() {
    return this.client;
  }

  async disconnect() {
    await this.client.quit();
  }
}

const redisClient = new RedisClient();
Object.freeze(redisClient);

export default redisClient;
export const redis = redisClient.getClient();
