import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { RedisService } from './redis.service';

@Injectable()
export class ReportCacheService {
  private readonly logger = new Logger(ReportCacheService.name);
  private readonly cachePrefix = 'report:';
  private readonly defaultTtl: number;

  constructor(
    private readonly redisService: RedisService,
    private readonly configService: ConfigService,
  ) {
    this.defaultTtl = this.configService.get<number>('REPORT_CACHE_TTL', 3600);
  }

  async cacheSnapshot(
    reportCode: string,
    periodKey: string,
    data: any,
    ttlSeconds?: number,
  ): Promise<void> {
    const key = this.buildKey(reportCode, periodKey);
    await this.redisService.setJson(key, data, ttlSeconds || this.defaultTtl);
    this.logger.debug(`Cached report snapshot: ${key}`);
  }

  async getCachedSnapshot<T>(
    reportCode: string,
    periodKey: string,
  ): Promise<T | null> {
    const key = this.buildKey(reportCode, periodKey);
    const cached = await this.redisService.getJson<T>(key);
    if (cached) {
      this.logger.debug(`Cache hit for report snapshot: ${key}`);
    }
    return cached;
  }

  async invalidateSnapshot(reportCode: string, periodKey: string): Promise<void> {
    const key = this.buildKey(reportCode, periodKey);
    await this.redisService.del(key);
    this.logger.debug(`Invalidated report cache: ${key}`);
  }

  async invalidateReportCache(reportCode: string): Promise<void> {
    const pattern = `${this.cachePrefix}${reportCode}:*`;
    const keys = await this.redisService.keys(pattern);
    for (const key of keys) {
      await this.redisService.del(key);
    }
    this.logger.debug(`Invalidated all cache for report: ${reportCode}`);
  }

  private buildKey(reportCode: string, periodKey: string): string {
    return `${this.cachePrefix}${reportCode}:${periodKey}`;
  }
}
