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

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

/** Update an exam — fields, status, and the publish flags. Publishing the
    schedule locks paper add/edit/delete; publishing the result locks marks
    input (admin must unpublish to allow edit again). */
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 exam = await prisma.cuExam.findFirst({
    where: { id: Number(id), institutionId: session.institutionId },
    select: { id: true, startDate: true },
  });
  if (!exam) return NextResponse.json({ error: "Not found" }, { status: 404 });

  try {
    const body = await req.json();
    const data: Record<string, unknown> = {};

    if (body.name !== undefined) data.name = String(body.name).trim();
    if (body.nameBn !== undefined) data.nameBn = String(body.nameBn).trim() || null;
    if (body.examType !== undefined) data.examType = String(body.examType);
    if (body.sessionYear !== undefined) data.sessionYear = String(body.sessionYear).trim() || null;
    if (body.status !== undefined) data.status = String(body.status);
    if (body.note !== undefined) data.note = String(body.note).trim() || null;
    for (const key of ["startDate", "endDate"] as const) {
      if (body[key] !== undefined) {
        const s = String(body[key]).slice(0, 10);
        data[key] = /^\d{4}-\d{2}-\d{2}$/.test(s) ? new Date(`${s}T00:00:00Z`) : null;
      }
    }
    if (data.startDate && data.endDate && (data.endDate as Date) < (data.startDate as Date)) {
      return NextResponse.json({ error: "END_BEFORE_START" }, { status: 400 });
    }
    if (body.schedulePublished !== undefined) {
      data.schedulePublished = !!body.schedulePublished;
      data.schedulePublishedAt = body.schedulePublished ? new Date() : null;
    }
    if (body.resultPublished !== undefined) {
      data.resultPublished = !!body.resultPublished;
      data.resultPublishedAt = body.resultPublished ? new Date() : null;
    }

    const updated = await prisma.cuExam.update({
      where: { id: exam.id },
      data,
      include: {
        program: { select: { id: true, name: true, nameBn: true, gradeScale: true } },
        term: { select: { id: true, name: true, nameBn: true } },
        _count: { select: { schedules: true } },
      },
    });
    return NextResponse.json({ exam: { ...updated, paperCount: updated._count.schedules } });
  } catch {
    return NextResponse.json({ error: "Could not update exam" }, { status: 500 });
  }
}

/** Delete an exam and its schedules/marks. */
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 exam = await prisma.cuExam.findFirst({
    where: { id: Number(id), institutionId: session.institutionId },
    select: { id: true },
  });
  if (!exam) return NextResponse.json({ error: "Not found" }, { status: 404 });

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