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

export async function DELETE(_req: Request, { params }: { params: Promise<{ id: string }> }) {
  const session = await getSession();
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { id } = await params;

  const appointment = await prisma.appointment.findFirst({
    where: { id, clinicId: session.id },
  });
  if (!appointment) return NextResponse.json({ error: "Not found" }, { status: 404 });

  // Delete scheduled reminders first, then appointment
  await prisma.scheduledReminder.deleteMany({ where: { appointmentId: id } });
  await prisma.appointment.delete({ where: { id } });

  return NextResponse.json({ ok: true });
}
