import { Injectable } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { ConfigService } from '@nestjs/config';
import { InjectRepository } from '@nestjs/typeorm';
import { LessThan, Repository } from 'typeorm';
import { LoggingService } from 'src/database/logging/logging.service';
import { Notification } from './entities/notification.entity';

@Injectable()
export class NotificationRetentionScheduler {
  constructor(
    @InjectRepository(Notification)
    private readonly repository: Repository<Notification>,
    private readonly configService: ConfigService,
    private readonly logger: LoggingService,
  ) {}

  @Cron(CronExpression.EVERY_DAY_AT_5AM)
  async cleanupOldNotifications(): Promise<void> {
    const retentionDays = this.configService.get<number>('app.logRetentionDays');
    const cutoff = new Date();
    cutoff.setUTCDate(cutoff.getUTCDate() - retentionDays);

    try {
      const result = await this.repository.delete({ createdAt: LessThan(cutoff) });

      await this.logger.info({
        event: 'notification_retention_cleanup_run',
        details: `deletedCount=${result.affected ?? 0} retentionDays=${retentionDays}`,
        userId: -1,
      });
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      await this.logger.error({
        event: 'notification_retention_cleanup_run_fail',
        details: errorMessage,
        userId: -1,
      });
    }
  }
}
