import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireRole } from "@/lib/auth";
import { validateSchedule, type ScheduleBody } from "@/lib/schedule";

type Params = { params: Promise<{ id: string }> };

/** Update a schedule entry. */
export async function PUT(req: Request, { params }: Params) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const { id } = await params;

  try {
    const existing = await prisma.classSchedule.findFirst({
      where: { id: Number(id), institutionId: session.institutionId },
    });
    if (!existing) return NextResponse.json({ error: "Not found" }, { status: 404 });

    const body = (await req.json()) as ScheduleBody;
    const result = await validateSchedule(session.institutionId, body, existing.id);
    if ("error" in result) {
      return NextResponse.json({ error: result.error }, { status: result.status });
    }

    await prisma.classSchedule.update({
      where: { id: existing.id },
      data: result.data,
    });
    return NextResponse.json({ success: true });
  } catch {
    return NextResponse.json({ error: "Could not update schedule" }, { status: 500 });
  }
}

/** Delete a schedule entry. */
export async function DELETE(_req: Request, { params }: Params) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const { id } = await params;

  const res = await prisma.classSchedule.deleteMany({
    where: { id: Number(id), institutionId: session.institutionId },
  });
  if (res.count === 0) return NextResponse.json({ error: "Not found" }, { status: 404 });
  return NextResponse.json({ success: true });
}
