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

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

/** Edit a paper — same rules as create; blocked while the schedule is published. */
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 schedule = await prisma.cuExamSchedule.findFirst({
    where: { id: Number(id), institutionId: session.institutionId },
    select: { id: true, exam: { select: { schedulePublished: true } } },
  });
  if (!schedule) return NextResponse.json({ error: "Not found" }, { status: 404 });
  if (schedule.exam.schedulePublished) {
    return NextResponse.json({ error: "SCHEDULE_PUBLISHED" }, { status: 409 });
  }

  try {
    const body = await req.json();
    const data: Record<string, unknown> = {};
    if (body.examDate !== undefined) {
      const s = String(body.examDate).slice(0, 10);
      data.examDate = /^\d{4}-\d{2}-\d{2}$/.test(s) ? new Date(`${s}T00:00:00Z`) : null;
    }
    for (const key of ["startTime", "endTime"] as const) {
      if (body[key] !== undefined) {
        data[key] = /^\d{2}:\d{2}$/.test(String(body[key])) ? String(body[key]) : null;
      }
    }
    if (body.room !== undefined) data.room = String(body.room).trim() || null;
    if (body.note !== undefined) data.note = String(body.note).trim() || null;
    if (body.fullMarks !== undefined && body.fullMarks !== "") {
      const n = Number(body.fullMarks);
      if (!Number.isFinite(n) || n <= 0) return NextResponse.json({ error: "Invalid full marks" }, { status: 400 });
      data.fullMarks = n;
    }
    if (body.passMarks !== undefined && body.passMarks !== "") {
      const n = Number(body.passMarks);
      if (!Number.isFinite(n) || n < 0) return NextResponse.json({ error: "Invalid pass marks" }, { status: 400 });
      data.passMarks = n;
    }
    if (
      data.fullMarks !== undefined && data.passMarks !== undefined &&
      (data.passMarks as number) > (data.fullMarks as number)
    ) {
      return NextResponse.json({ error: "PASS_EXCEEDS_MARKS" }, { status: 400 });
    }

    const updated = await prisma.cuExamSchedule.update({
      where: { id: schedule.id },
      data,
      include: {
        course: { select: { id: true, code: true, name: true, nameBn: true, credits: true, courseType: true, term: { select: { name: true, nameBn: true } } } },
      },
    });
    return NextResponse.json({ schedule: updated });
  } catch {
    return NextResponse.json({ error: "Could not update paper" }, { status: 500 });
  }
}

/** Delete a paper (and its marks); blocked while the schedule is published. */
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 schedule = await prisma.cuExamSchedule.findFirst({
    where: { id: Number(id), institutionId: session.institutionId },
    select: { id: true, exam: { select: { schedulePublished: true } } },
  });
  if (!schedule) return NextResponse.json({ error: "Not found" }, { status: 404 });
  if (schedule.exam.schedulePublished) {
    return NextResponse.json({ error: "SCHEDULE_PUBLISHED" }, { status: 409 });
  }

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