import Redis from 'ioredis';

// Create Redis client
const redis = new Redis({
  host: process.env.REDIS_HOST || 'localhost',
  port: Number(process.env.REDIS_PORT || 6379),
  password: process.env.REDIS_PASSWORD,
  retryStrategy(times) {
    const delay = Math.min(times * 50, 2000);
    return delay;
  },
  maxRetriesPerRequest: 3,
  lazyConnect: true,
});

// Handle connection events
redis.on('connect', () => {
  console.log('✓ Redis connected');
});

redis.on('error', (err) => {
  console.error('Redis error:', err.message);
});

redis.on('close', () => {
  console.log('Redis connection closed');
});

// Connect to Redis - DISABLED for Mode6Test
// (async () => {
//   try {
//     await redis.connect();
//   } catch (err) {
//     console.error('Failed to connect to Redis:', err);
//   }
// })();

/**
 * Get a value from cache
 */
export async function getCache(key: string): Promise<any | null> {
  try {
    const value = await redis.get(key);
    if (!value) return null;
    return JSON.parse(value);
  } catch (err) {
    console.error(`Cache get error for key "${key}":`, err);
    return null;
  }
}

/**
 * Set a value in cache with TTL in seconds
 */
export async function setCache(key: string, value: any, ttl: number = 300): Promise<boolean> {
  try {
    const serialized = JSON.stringify(value);
    await redis.setex(key, ttl, serialized);
    return true;
  } catch (err) {
    console.error(`Cache set error for key "${key}":`, err);
    return false;
  }
}

/**
 * Delete a key from cache
 */
export async function deleteCache(key: string): Promise<boolean> {
  try {
    await redis.del(key);
    return true;
  } catch (err) {
    console.error(`Cache delete error for key "${key}":`, err);
    return false;
  }
}

/**
 * Clear all cache keys matching a pattern
 */
export async function clearCachePattern(pattern: string): Promise<number> {
  try {
    const keys = await redis.keys(pattern);
    if (keys.length === 0) return 0;
    await redis.del(...keys);
    return keys.length;
  } catch (err) {
    console.error(`Cache clear error for pattern "${pattern}":`, err);
    return 0;
  }
}

/**
 * Check if Redis is connected
 */
export function isRedisConnected(): boolean {
  return redis.status === 'ready';
}

export default redis;
