import { NextResponse } from "next/server";
import { prisma } from "@/infrastructure/db/prisma";
import { sendDailyAgenda } from "@/infrastructure/email/smtp";

export async function POST() {
  try {
    console.log("[Trigger] Manual trigger for daily agenda");

    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(`[Trigger] Found ${appointments.length} appointments for tomorrow`);

    const adminEmail = process.env.ADMIN_EMAIL;
    if (!adminEmail) {
      return NextResponse.json(
        { success: false, message: "ADMIN_EMAIL not configured" },
        { status: 500 }
      );
    }

    await sendDailyAgenda(adminEmail, appointments);

    return NextResponse.json({
      success: true,
      message: "Daily agenda email sent successfully",
      appointmentsCount: appointments.length,
    });
  } catch (error) {
    console.error("[Trigger] Error:", error);
    return NextResponse.json(
      { success: false, message: "Error sending daily agenda" },
      { status: 500 }
    );
  }
}
