import { Injectable } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, LessThan, MoreThan, Between } from 'typeorm';
import { AiInterviewSchedules } from './entities/ai_interview_schedules.entity';

@Injectable()
export class ReminderCronService {
  constructor(
    @InjectRepository(AiInterviewSchedules)
    private readonly scheduleRepository: Repository<AiInterviewSchedules>,
  ) {}

  /**
   * Send 24-hour reminders every hour
   * Runs at the start of every hour
   */
  @Cron(CronExpression.EVERY_HOUR)
  async send24HourReminders() {
    console.log('Running 24-hour reminder cron job...');

    const now = new Date();
    const twentyFourHoursFromNow = new Date(
      now.getTime() + 24 * 60 * 60 * 1000,
    );
    const twentyFiveHoursFromNow = new Date(
      now.getTime() + 25 * 60 * 60 * 1000,
    );

    try {
      // Find schedules that are 24-25 hours away and haven't sent 24h reminder
      const schedules = await this.scheduleRepository.find({
        where: {
          status: 'SCHEDULED',
          scheduled_at: Between(twentyFourHoursFromNow, twentyFiveHoursFromNow),
          reminder_1day_sent: false,
        },
      });

      console.log(`Found ${schedules.length} schedules for 24-hour reminders`);

      for (const schedule of schedules) {
        try {
          // TODO: Implement email sending with EmailService
          // You'll need to fetch seeker/job data and send email

          // Mark as sent
          await this.scheduleRepository.update(schedule.id, {
            reminder_1day_sent: true,
          });

          console.log(`24-hour reminder sent for schedule ${schedule.id}`);
        } catch (error) {
          console.error(
            `Failed to send 24-hour reminder for schedule ${schedule.id}:`,
            error,
          );
        }
      }
    } catch (error) {
      console.error('Error in 24-hour reminder cron job:', error);
    }
  }

  /**
   * Send 1-hour reminders every 15 minutes
   * Runs at 0, 15, 30, 45 minutes past every hour
   */
  @Cron('0,15,30,45 * * * *')
  async send1HourReminders() {
    console.log('Running 1-hour reminder cron job...');

    const now = new Date();
    const oneHourFromNow = new Date(now.getTime() + 60 * 60 * 1000);
    const oneHourFifteenMinutesFromNow = new Date(
      now.getTime() + 75 * 60 * 1000,
    );

    try {
      // Find schedules that are 60-75 minutes away and haven't sent 1h reminder
      const schedules = await this.scheduleRepository.find({
        where: {
          status: 'SCHEDULED',
          scheduled_at: Between(oneHourFromNow, oneHourFifteenMinutesFromNow),
          reminder_1hour_sent: false,
        },
      });

      console.log(`Found ${schedules.length} schedules for 1-hour reminders`);

      for (const schedule of schedules) {
        try {
          // TODO: Implement email sending with EmailService
          // You'll need to fetch seeker/job data and send email

          // Mark as sent
          await this.scheduleRepository.update(schedule.id, {
            reminder_1hour_sent: true,
          });

          console.log(`1-hour reminder sent for schedule ${schedule.id}`);
        } catch (error) {
          console.error(
            `Failed to send 1-hour reminder for schedule ${schedule.id}:`,
            error,
          );
        }
      }
    } catch (error) {
      console.error('Error in 1-hour reminder cron job:', error);
    }
  }

  /**
   * Mark NO_SHOW for missed interviews
   * Runs every 30 minutes
   */
  @Cron('*/30 * * * *')
  async markNoShows() {
    console.log('Running NO_SHOW check cron job...');

    const now = new Date();
    // Check interviews that were scheduled more than 2 hours ago
    const twoHoursAgo = new Date(now.getTime() - 2 * 60 * 60 * 1000);

    try {
      // Find schedules that are past scheduled time and still SCHEDULED
      const schedules = await this.scheduleRepository.find({
        where: {
          status: 'SCHEDULED',
          scheduled_at: LessThan(twoHoursAgo),
        },
      });

      console.log(`Found ${schedules.length} potential NO_SHOW schedules`);

      for (const schedule of schedules) {
        try {
          await this.scheduleRepository.update(schedule.id, {
            status: 'NO_SHOW',
          });

          console.log(`Marked schedule ${schedule.id} as NO_SHOW`);
        } catch (error) {
          console.error(
            `Failed to mark NO_SHOW for schedule ${schedule.id}:`,
            error,
          );
        }
      }
    } catch (error) {
      console.error('Error in NO_SHOW check cron job:', error);
    }
  }
}
