import { Injectable, Logger, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { PrismaService } from '../../infrastructure/database/prisma.service';

const RETENTION_DAYS = 30;
const CLEANUP_INTERVAL_MS = 24 * 60 * 60 * 1000; // daily

@Injectable()
export class MetricsCleanupService implements OnModuleInit, OnModuleDestroy {
  private readonly logger = new Logger(MetricsCleanupService.name);
  private timer: ReturnType<typeof setInterval> | null = null;

  constructor(private readonly prisma: PrismaService) {}

  async onModuleInit() {
    await this.cleanup().catch(() => {});
    this.timer = setInterval(() => this.cleanup().catch(() => {}), CLEANUP_INTERVAL_MS);
  }

  onModuleDestroy() {
    if (this.timer) clearInterval(this.timer);
  }

  async cleanup(): Promise<number> {
    const cutoff = new Date(Date.now() - RETENTION_DAYS * 86400000);
    try {
      const result = await this.prisma.apiMetric.deleteMany({
        where: { createdAt: { lt: cutoff } },
      });
      if (result.count > 0) {
        this.logger.log(`Cleaned up ${result.count} ApiMetric records older than ${RETENTION_DAYS} days`);
      }
      return result.count;
    } catch (err: any) {
      this.logger.warn(`ApiMetric cleanup failed: ${err.message}`);
      return 0;
    }
  }
}
