import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { LeaveRequest, LeaveStatus } from './entities/leave-request.entity';
import { LeavesAcquisitionService } from './leaves-acquisition.service';

@Injectable()
export class LeavesScheduler {
  private readonly logger = new Logger(LeavesScheduler.name);

  constructor(
    @InjectRepository(LeaveRequest)
    private readonly leaveRequestRepo: Repository<LeaveRequest>,

    private readonly acquisitionService: LeavesAcquisitionService,
  ) {}

  // Relance hebdomadaire des demandes en attente
  @Cron(CronExpression.EVERY_WEEK)
  async sendReminders() {
    // TODO Sprint 4 — brancher MailService
    const pending = await this.leaveRequestRepo.find({
      where: [
        { status: LeaveStatus.PENDING_N1 },
        { status: LeaveStatus.PENDING_N2 },
        { status: LeaveStatus.PENDING_N3 },
      ],
      relations: ['user', 'leave_type'],
    });

    this.logger.log(`[CRON] ${pending.length} demande(s) en attente de relance`);
  }

  // Acquisition mensuelle — le 1er de chaque mois à 00h01
  @Cron('1 0 1 * *')
  async monthlyAcquisition() {
    this.logger.log('[CRON] Lancement acquisition mensuelle...');
    await this.acquisitionService.runMonthlyAcquisition();
  }

  // Acquisition annuelle — le 1er janvier à 00h05
  @Cron('5 0 1 1 *')
  async annualAcquisition() {
    this.logger.log('[CRON] Lancement acquisition annuelle...');
    await this.acquisitionService.runAnnualAcquisition();
  }
}