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

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

/** Update an offering (section, teacher, seats, note). */
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 offering = await prisma.cuOffering.findFirst({
    where: { id: Number(id), institutionId: session.institutionId },
    select: { id: true, courseId: true, sessionYear: true, section: true },
  });
  if (!offering) return NextResponse.json({ error: "Not found" }, { status: 404 });

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

    if (body.sessionYear !== undefined || body.section !== undefined) {
      const sessionYear = body.sessionYear !== undefined ? String(body.sessionYear).trim() : offering.sessionYear;
      const section = body.section !== undefined ? String(body.section).trim() : (offering.section ?? "");
      if (!sessionYear) return NextResponse.json({ error: "Missing fields" }, { status: 400 });
      const dup = await prisma.cuOffering.findFirst({
        where: { courseId: offering.courseId, sessionYear, section: section || null, id: { not: offering.id } },
        select: { id: true },
      });
      if (dup) return NextResponse.json({ error: "OFFERING_EXISTS" }, { status: 409 });
      data.sessionYear = sessionYear;
      data.section = section || null;
    }
    if (body.staffId !== undefined) {
      const staffId = Number(body.staffId);
      if (Number.isFinite(staffId) && staffId > 0) {
        const staff = await prisma.staff.findFirst({
          where: { id: staffId, institutionId: session.institutionId },
          select: { id: true },
        });
        if (!staff) return NextResponse.json({ error: "Invalid teacher" }, { status: 400 });
        data.staffId = staff.id;
      } else {
        data.staffId = null;
      }
    }
    if (body.maxSeats !== undefined) {
      const n = Number(body.maxSeats);
      data.maxSeats = Number.isFinite(n) && n > 0 ? Math.round(n) : null;
    }
    if (body.note !== undefined) data.note = String(body.note).trim() || null;

    const updated = await prisma.cuOffering.update({
      where: { id: offering.id },
      data,
      include: {
        course: { select: { id: true, code: true, name: true, nameBn: true, credits: true, courseType: 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, designation: true } },
      },
    });
    return NextResponse.json({ offering: updated });
  } catch {
    return NextResponse.json({ error: "Could not update offering" }, { status: 500 });
  }
}

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

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