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

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

/** Update a routine slot (times/room). */
export async function PATCH(req: Request, { params }: Params) {
  const session = await requireCampusInstitution();
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { id } = await params;
  const slot = await prisma.cuCourseSlot.findFirst({
    where: { id: Number(id), institutionId: session.institutionId },
    select: { id: true, offeringId: true, dayOfWeek: true },
  });
  if (!slot) return NextResponse.json({ error: "Not found" }, { status: 404 });

  try {
    const body = await req.json();
    const data: Record<string, unknown> = {};
    if (body.dayOfWeek !== undefined) data.dayOfWeek = String(body.dayOfWeek);
    if (body.room !== undefined) data.room = String(body.room).trim() || null;
    if (body.note !== undefined) data.note = String(body.note).trim() || null;
    for (const key of ["startTime", "endTime"] as const) {
      if (body[key] !== undefined) {
        if (!/^\d{2}:\d{2}$/.test(String(body[key]))) continue;
        data[key] = String(body[key]);
      }
    }
    const start = (data.startTime as string) ?? undefined;
    const end = (data.endTime as string) ?? undefined;
    if (start && end && end <= start) {
      return NextResponse.json({ error: "END_BEFORE_START" }, { status: 400 });
    }

    const updated = await prisma.cuCourseSlot.update({
      where: { id: slot.id },
      data,
      include: {
        offering: {
          select: {
            id: true, sessionYear: true, section: true,
            course: { select: { id: true, code: true, name: true, nameBn: true, credits: true, program: { select: { id: true, name: true, nameBn: true } }, term: { select: { id: true, name: true, nameBn: true } } } },
            staff: { select: { id: true, name: true, nameBn: true } },
          },
        },
      },
    });
    return NextResponse.json({ slot: updated });
  } catch {
    return NextResponse.json({ error: "Could not update slot" }, { status: 500 });
  }
}

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

  const { id } = await params;
  const slot = await prisma.cuCourseSlot.findFirst({
    where: { id: Number(id), institutionId: session.institutionId },
    select: { id: true },
  });
  if (!slot) return NextResponse.json({ error: "Not found" }, { status: 404 });

  try {
    await prisma.cuCourseSlot.delete({ where: { id: slot.id } });
    return NextResponse.json({ ok: true });
  } catch {
    return NextResponse.json({ error: "Could not delete slot" }, { status: 500 });
  }
}
