import { notifyUser } from "./notifications";
import { prisma } from "./prisma";

const LOOKAHEAD_MS = 24 * 60 * 60 * 1000;
const CHECK_INTERVAL_MS = 5 * 60 * 1000;

export async function checkDueDateReminders() {
  const now = new Date();
  const horizon = new Date(now.getTime() + LOOKAHEAD_MS);

  const cards = await prisma.card.findMany({
    where: {
      isCompleted: false,
      isArchived: false,
      dueDate: { not: null, lte: horizon },
      dueDateNotifiedAt: null,
    },
    include: { members: true },
  });

  for (const card of cards) {
    const isOverdue = card.dueDate! < now;
    for (const member of card.members) {
      await notifyUser({
        recipientId: member.userId,
        type: "DUE_DATE",
        message: isOverdue
          ? `"${card.title}" is now overdue`
          : `"${card.title}" is due within 24 hours`,
        cardId: card.id,
        boardId: card.boardId,
      });
    }

    await prisma.card.update({
      where: { id: card.id },
      data: { dueDateNotifiedAt: now },
    });
  }
}

export function startDueDateReminderJob() {
  checkDueDateReminders().catch((err) => console.error("[due-date-reminders]", err));
  setInterval(() => {
    checkDueDateReminders().catch((err) => console.error("[due-date-reminders]", err));
  }, CHECK_INTERVAL_MS);
}
