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

const CLEANUP_INTERVAL_MS = 60 * 60 * 1000; // hourly

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

  constructor(private readonly prisma: PrismaService) {}

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

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

  /** Delete expired snapshots. Safe to hard-delete: snapshots are cache artifacts with no FK constraints. */
  async cleanupExpired(): Promise<{ deleted: number }> {
    const result = await this.prisma.learningAnalysisSnapshot.deleteMany({
      where: { expiresAt: { lt: new Date() } },
    });
    if (result.count > 0) {
      this.logger.log(`Cleaned up ${result.count} expired snapshot(s)`);
    }
    return { deleted: result.count };
  }
}
