import { createClient } from 'redis';
import { config } from './index.js';
import { logger } from '../utils/logger.js';

export type RedisClient = ReturnType<typeof createClient>;

let redisClient: RedisClient | null = null;

export async function initRedis(): Promise<RedisClient> {
  if (redisClient) {
    return redisClient;
  }

  redisClient = createClient({
    socket: {
      host: config.redis.host,
      port: config.redis.port,
      connectTimeout: 5000,
      reconnectStrategy: (retries) => {
        if (retries > 3) {
          return new Error('Redis connection failed after 3 retries');
        }
        return Math.min(retries * 100, 3000);
      },
    },
    password: config.redis.password || undefined,
    database: config.redis.db,
  });

  redisClient.on('error', (err) => {
    logger.error('Redis Client Error:', err.message);
  });

  redisClient.on('connect', () => {
    logger.info('Redis Client Connected');
  });

  await redisClient.connect();

  return redisClient;
}

export function getRedisClient(): RedisClient {
  if (!redisClient) {
    throw new Error('Redis client not initialized');
  }
  return redisClient;
}

export async function closeRedis(): Promise<void> {
  if (redisClient) {
    await redisClient.quit();
    redisClient = null;
  }
}
