import { connectDB } from "@/lib/db";
import { Todo } from "@/models/Todo";
import { notifyRecipients } from "@/lib/notifications";

// Täglicher Sweep: für offene ToDos, die innerhalb der nächsten 24 h fällig
// sind (oder schon überfällig) und für dieses Datum noch keine Erinnerung
// hatten, die Zuständigen benachrichtigen. Beobachter bewusst nicht.
export async function runTodoDueReminderSweep() {
  await connectDB();
  const cutoff = new Date(Date.now() + 24 * 60 * 60 * 1000);

  const todos = await Todo.find({
    status: { $ne: "done" },
    dueDate: { $ne: null, $lte: cutoff },
    $or: [{ dueReminderSentAt: null }, { dueReminderSentAt: { $exists: false } }],
  })
    .select("title dueDate assignedToId additionalAssigneeIds")
    .lean();

  let sent = 0;
  for (const t of todos) {
    const recipients = [String(t.assignedToId), ...(t.additionalAssigneeIds || []).map(String)];
    const when = t.dueDate ? new Date(t.dueDate).toLocaleDateString("de-DE") : "";
    await notifyRecipients(recipients, {
      type: "todo",
      title: `ToDo fällig: ${t.title}`,
      body: `Fällig am ${when}.`,
      link: `/de/admin/todos#${t._id}`,
    });
    await Todo.findByIdAndUpdate(t._id, { dueReminderSentAt: new Date() });
    sent++;
  }
  return { checked: todos.length, sent };
}
