import { createClient, RedisClientType } from 'redis';

class RedisUtil {
  private client: RedisClientType | null = null;
  private static instance: RedisUtil;

  private constructor() {}

  public static getInstance(): RedisUtil {
    if (!RedisUtil.instance) {
      RedisUtil.instance = new RedisUtil();
    }
    return RedisUtil.instance;
  }

  async connect(): Promise<RedisClientType> {
    if (!this.client) {
      this.client = createClient({
        url: process.env.REDIS_URL || 'redis://127.0.0.1:6379'
      });

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

      await this.client.connect();
    }
    return this.client;
  }

  async disconnect(): Promise<void> {
    if (this.client) {
      await this.client.disconnect();
      this.client = null;
    }
  }

  async setSessionKey(userId: number, sessionKey: string, ttlSeconds: number = 7200): Promise<void> {
    const client = await this.connect();
    const key = `session_key:${userId}`;
    await client.set(key, sessionKey, {
      EX: ttlSeconds // 默认2小时过期，与微信session_key有效期一致
    });
  }

  async getSessionKey(userId: number): Promise<string | null> {
    const client = await this.connect();
    const key = `session_key:${userId}`;
    return await client.get(key);
  }

  async deleteSessionKey(userId: number): Promise<void> {
    const client = await this.connect();
    const key = `session_key:${userId}`;
    await client.del(key);
  }

  async isSessionKeyValid(userId: number): Promise<boolean> {
    const sessionKey = await this.getSessionKey(userId);
    return !!sessionKey;
  }
}

export const redisUtil = RedisUtil.getInstance();