import cron from "node-cron";
import { prisma } from "@/infrastructure/db/prisma";
import { sendDailyAgenda } from "@/infrastructure/email/smtp";

console.log("[Jobs] Initializing daily agenda job...");

cron.schedule("0 22 * * *", async () => {
  console.log("[Jobs] Running daily agenda job at 10 PM");

  try {
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    tomorrow.setHours(0, 0, 0, 0);

    const nextDay = new Date(tomorrow);
    nextDay.setDate(nextDay.getDate() + 1);
    nextDay.setHours(23, 59, 59, 999);

    const appointments = await prisma.appointment.findMany({
      where: {
        date: {
          gte: tomorrow,
          lte: nextDay,
        },
        status: "confirmed",
      },
      include: {
        patient: true,
        payment: true,
      },
      orderBy: { date: "asc" },
    });

    console.log(`[Jobs] Found ${appointments.length} appointments for tomorrow`);

    const adminEmail = process.env.ADMIN_EMAIL;
    if (adminEmail) {
      await sendDailyAgenda(adminEmail, appointments);
      console.log(`[Jobs] Daily agenda sent successfully to ${adminEmail}`);
    } else {
      console.error("[Jobs] ADMIN_EMAIL not set");
    }
  } catch (error) {
    console.error("[Jobs] Error sending daily agenda:", error);
  }
});

console.log("[Jobs] Daily agenda job initialized");
