const db = require("../db/models");
const { reminderMinutes, scheduledReminderAt } = require("../security/reminders");

async function runReminderSchedule() {
  const settings = await db.workspace_settings.findByPk("default");

  if (settings && !settings.reminders_enabled) {
    console.log(JSON.stringify({ event: "coaching_reminders_disabled" }));
    return;
  }

  const now = new Date();
  const readyReminders = await db.coaching_reminder_deliveries.findAll({
    where: { status: "ready" },
    include: [{ model: db.clients, as: "client", required: true }],
  });

  let stale = 0;
  for (const reminder of readyReminders) {
    const currentSession = reminder.client.next_session_at;
    const sessionChanged = !currentSession || new Date(currentSession).getTime() !== new Date(reminder.session_at).getTime();
    if (!reminder.client.reminders_enabled || sessionChanged || new Date(reminder.session_at) <= now) {
      await reminder.destroy();
      stale += 1;
    }
  }

  const nextDay = new Date(now.getTime() + 25 * 60 * 60 * 1000);
  const clients = await db.clients.findAll({
    where: {
      reminders_enabled: true,
      next_session_at: { [db.Sequelize.Op.gt]: now, [db.Sequelize.Op.lt]: nextDay },
    },
  });
  let ready = 0;

  for (const client of clients) {
    const minutes = reminderMinutes(client.reminder_minutes, settings?.default_reminder_minutes || 60);
    const scheduledFor = scheduledReminderAt(client.next_session_at, minutes);

    if (scheduledFor > now) {
      continue;
    }

    const [, created] = await db.coaching_reminder_deliveries.findOrCreate({
      where: {
        clientId: client.id,
        session_at: client.next_session_at,
        scheduled_for: scheduledFor,
      },
      defaults: { status: "ready" },
    });

    if (created) ready += 1;
  }

  console.log(JSON.stringify({ event: "coaching_reminders_scheduled", ready, stale_removed: stale }));
}

if (require.main === module) {
  runReminderSchedule()
    .then(() => db.sequelize.close())
    .catch(async (error) => {
      console.error("Coaching reminder scheduling failed", error);
      await db.sequelize.close();
      process.exitCode = 1;
    });
}

module.exports = { runReminderSchedule };
