import { Injectable } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { DatabaseService, logger } from '../../config';
import { ProbationStatusEnum, TaskStatusEnum } from '../../config/database/entities';
import { NotificationsService } from '../notifications/notifications.service';

@Injectable()
export class OnboardingCronService {
  constructor(
    private readonly db: DatabaseService,
    private readonly notificationsService: NotificationsService,
  ) {}

  // Daily Cron Job at 08:00 AM
  @Cron(CronExpression.EVERY_DAY_AT_8AM)
  async handleDailyOnboardingAlerts() {
    logger.info('Running daily Onboarding & Probation automated check...');
    try {
      const now = new Date();
      const inSevenDays = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);

      // 1. Probation Reviews Due within 7 days
      const probationsDue = await this.db.probations.findMany({
        where: {
          status: ProbationStatusEnum.pending,
          review_due_date: { lte: inSevenDays },
        },
        include: { member: true, manager: true },
      });

      for (const prob of probationsDue) {
        if (prob.manager_id) {
          await this.notificationsService.sendNotification({
            owner_id: prob.owner_id,
            title: 'Probation Review Due Soon',
            message: `Probation review for ${prob.member?.first_name} ${prob.member?.last_name} is due by ${prob.current_end_date ? new Date(prob.current_end_date).toLocaleDateString() : 'soon'}.`,
            type: 'RECRUITMENT' as any,
            member_id: prob.manager_id,
            reference_id: prob.id,
          });
        }
      }

      // 2. Overdue Onboarding Tasks Alert
      const overdueTasks = await this.db.onboarding_tasks.findMany({
        where: {
          status: TaskStatusEnum.pending,
          due_date: { lt: now },
        },
        include: { onboarding_case: true },
      });

      for (const task of overdueTasks) {
        if (task.assigned_member_id) {
          await this.notificationsService.sendNotification({
            owner_id: task.onboarding_case.owner_id,
            title: 'Overdue Onboarding Task',
            message: `Onboarding task "${task.title}" is overdue. Please complete it as soon as possible.`,
            type: 'RECRUITMENT' as any,
            member_id: task.assigned_member_id,
            reference_id: task.id,
          });
        }
      }

      logger.info(
        `Automated check completed. Processed ${probationsDue.length} probation reminders and ${overdueTasks.length} overdue tasks.`,
      );
    } catch (error) {
      logger.error('Error running daily onboarding alerts cron', error);
    }
  }
}
