import { Inject, Injectable } from '@nestjs/common';
import { REDIS_CLIENT } from './redis.constants';

/**
 * RedisService — wrapper around ioredis client.
 *
 * Used for:
 * - Permission caching per user session (CLAUDE.md)
 * - Cache invalidation on permission changes (CLAUDE.md line 76)
 */
@Injectable()
export class RedisService {
  constructor(@Inject(REDIS_CLIENT) private readonly client: any) {}

  async get(key: string): Promise<string | null> {
    return this.client.get(key);
  }

  async set(key: string, value: string, ttlSeconds?: number): Promise<void> {
    if (ttlSeconds) {
      await this.client.set(key, value, 'EX', ttlSeconds);
    } else {
      await this.client.set(key, value);
    }
  }

  async del(key: string): Promise<void> {
    await this.client.del(key);
  }

  /**
   * Invalidate all keys matching a pattern.
   * Used when permissions change → invalidate Redis cache.
   */
  async invalidateByPattern(pattern: string): Promise<void> {
    const keys = await this.client.keys(pattern);
    if (keys.length > 0) {
      await this.client.del(...keys);
    }
  }
}
