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

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

  constructor(private readonly em: EntityManager) {}

  // run every day at 03:00 (3:00 AM)
  @Cron('0 3 * * *', {
    name: 'deleteOldPagers',
    timeZone: 'UTC',
  })
  async handleCron() {
    try {
      this.logger.debug('Starting daily pager cleanup (removing pagers 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 oldPagers = await this.em.find(Pager, {
        createdAt: { $lt: twentyFourHoursAgo },
      });

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

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

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

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

