const redisPromise = require("./redis-loader");

class RedisClient {
  constructor() {
    this.client = null;
    this.isConnected = false;
  }

  async initialize() {
    if (this.client) return this;

    try {
      const redisModule = await redisPromise;
      this.client = redisModule.createClient({
        url: process.env.REDIS_URL || "redis://localhost:6379",
        socket: {
          reconnectStrategy: (retries) => {
            console.warn(`Redis reconnect attempt #${retries}`);
            return Math.min(retries * 50, 2000);
          },
        },
      });

      this.client.on("error", (err) => {
        this.isConnected = false;
        console.error("Redis Client Error:", err);
      });

      await this.client.connect();
      this.isConnected = true;
      console.log("Redis connected successfully");
    } catch (err) {
      console.warn("Redis not available, caching disabled", err.message);
      this.isConnected = false;
    }

    return this;
  }

  async get(key) {
    if (!this.isConnected) return null;
    try {
      return await this.client.get(key);
    } catch (err) {
      console.warn("Redis GET failed:", err.message);
      return null;
    }
  }

  async set(key, value, ttlSeconds) {
    if (!this.isConnected) return;
    try {
      if (ttlSeconds) {
        await this.client.setEx(key, ttlSeconds, value);
      } else {
        await this.client.set(key, value);
      }
    } catch (err) {
      console.warn("Redis SET failed:", err.message);
    }
  }

  async del(key) {
    if (!this.isConnected) return;
    try {
      await this.client.del(key);
    } catch (err) {
      console.warn("Redis DEL failed:", err.message);
    }
  }

  async resetAll() {
    if (!this.isConnected) return;
    await this.client.flushDb();
  }
}

module.exports = new RedisClient();
