import { toZonedTime } from 'date-fns-tz';
import Quiz from '../models/quiz';
import {
  notifyQuizStartReminder,
  notifyQuizEndingSoon,
  sendDailyAttendanceReminder,
} from '../services/notificationService';

const INTERVAL = 60 * 1000; // every minute
const KOLKATA_TZ = 'Asia/Kolkata';

const shouldRunDailyAttendanceReminder = (now: Date) => {
  const zoned = toZonedTime(now, KOLKATA_TZ);
  return zoned.getHours() === 10 && zoned.getMinutes() === 0;
};

const processQuizReminders = async () => {
  const now = new Date();
  const plus15 = new Date(now.getTime() + 15 * 60 * 1000);
  const plus60 = new Date(now.getTime() + 60 * 60 * 1000);

  const [startSoon, endingSoon] = await Promise.all([
    Quiz.find({
      status: 'active',
      start_datetime: { $gt: now, $lte: plus15 },
      end_datetime: { $gt: now },
    })
      .select('_id title start_datetime')
      .lean(),
    Quiz.find({
      status: 'active',
      end_datetime: { $gt: now, $lte: plus60 },
    })
      .select('_id title end_datetime')
      .lean(),
  ]);

  await Promise.all([
    ...startSoon.map((q) => notifyQuizStartReminder(q._id.toString(), q.title, new Date(q.start_datetime))),
    ...endingSoon.map((q) => notifyQuizEndingSoon(q._id.toString(), q.title, new Date(q.end_datetime))),
  ]);
};

export const runNotificationScheduler = async () => {
  await processQuizReminders();

  if (shouldRunDailyAttendanceReminder(new Date())) {
    await sendDailyAttendanceReminder();
  }
};

export const startNotificationCron = () => {
  runNotificationScheduler().catch((e) =>
    console.error('[Cron] Initial notification scheduler failed:', (e as Error).message),
  );

  setInterval(async () => {
    try {
      await runNotificationScheduler();
    } catch (error) {
      console.error('[Cron] Notification scheduler failed:', (error as Error).message);
    }
  }, INTERVAL);

  console.log('[Cron] Notification scheduler started (every 60s)');
};
