import { Injectable, Logger } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { EntityManager } from '@mikro-orm/postgresql';
import { Notification } from '../entities/notification.entity';

@Injectable()
export class NotificationCrone {
  private readonly logger = new Logger(NotificationCrone.name);

  constructor(private readonly em: EntityManager) {}

  // run every day at 03:00 (3:00 AM)
  @Cron('0 3 * * *', {
    name: 'deleteOldNotifications',
    timeZone: 'UTC',
  })
  async handleCron() {
    try {
      this.logger.debug('Starting daily notification cleanup (removing notifications older than 24 hours)');

      // Calculate the date 24 hours ago
      const twentyFourHoursAgo = new Date();
      twentyFourHoursAgo.setHours(twentyFourHoursAgo.getHours() - 24);

      // Find all notifications created more than 24 hours ago
      const oldNotifications = await this.em.find(Notification, {
        createdAt: { $lt: twentyFourHoursAgo },
      });

      if (!oldNotifications || oldNotifications.length === 0) {
        this.logger.debug('No old notifications found to delete');
        return;
      }

      this.logger.log(`Found ${oldNotifications.length} notifications older than 24 hours to delete`);

      // Delete the old notifications
      await this.em.removeAndFlush(oldNotifications);

      this.logger.log(`Successfully deleted ${oldNotifications.length} old notifications`);
    } catch (err) {
      this.logger.error(`NotificationCrone failed: ${err?.message}`, err);
    }
  }
}

