import { CalendarRepository } from './models/repositories/CalendarRepository';
import { BookingRepository } from './models/repositories/BookingRepository';
import { enqueueCalendarSync, enqueueNotification } from './jobs/queues';
import { initializeDatabase } from './models/index';

const TEN_MINUTES = 10 * 60 * 1000;
const THIRTY_MINUTES = 30 * 60 * 1000;
const ONE_HOUR = 60 * 60 * 1000;

async function startScheduler() {
  await initializeDatabase();
  const calendarRepo = new CalendarRepository();
  const bookingRepo = new BookingRepository();

  setInterval(async () => {
    try {
      const connections = await calendarRepo.findAllActiveConnections();
      for (const conn of connections) {
        await enqueueCalendarSync('syncFreeBusy', { connectionId: conn.id });
      }
    } catch (err) {
      console.error('syncFreeBusy schedule error:', err);
    }
  }, TEN_MINUTES);

  setInterval(async () => {
    try {
      await enqueueCalendarSync('refreshTokens', {});
    } catch (err) {
      console.error('refreshTokens schedule error:', err);
    }
  }, THIRTY_MINUTES);

  setInterval(async () => {
    try {
      for (const hoursBefore of [24, 1] as const) {
        const bookings = await bookingRepo.findForReminderWindow(hoursBefore);
        for (const b of bookings) {
          await enqueueNotification('sendReminder', { bookingId: b.id, hoursBefore });
        }
      }
    } catch (err) {
      console.error('reminder schedule error:', err);
    }
  }, ONE_HOUR);

  setInterval(async () => {
    try {
      const bookings = await bookingRepo.findPastMeetingsNeedingSurvey(1);
      for (const b of bookings) {
        await enqueueNotification('sendPostMeetingSurvey', { bookingId: b.id });
      }
    } catch (err) {
      console.error('post-meeting survey schedule error:', err);
    }
  }, ONE_HOUR);

  setInterval(async () => {
    try {
      const bookings = await bookingRepo.findPastMeetingsNeedingFollowUp(1);
      for (const b of bookings) {
        await enqueueNotification('sendFollowUp', { bookingId: b.id });
      }
    } catch (err) {
      console.error('follow-up schedule error:', err);
    }
  }, ONE_HOUR);

  console.log('Scheduler started');
}

startScheduler().catch(console.error);
