import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth";

// GET /api/reminders/failed
// Returns permanently failed reminders with details (why they failed, which patient)
export async function GET() {
  const session = await getSession();
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const clinicId = session.id;

  const reminders = await prisma.scheduledReminder.findMany({
    where: {
      status: "failed",
      retryCount: { gte: 3 },
      appointment: { clinicId },
    },
    include: {
      template: { select: { trigger: true, name: true } },
      appointment: {
        select: {
          dateTime: true,
          lead: { select: { name: true, phone: true } },
        },
      },
    },
    orderBy: { scheduledFor: "desc" },
    take: 50,
  });

  return NextResponse.json(reminders);
}
