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

/** Degree programs of the institution (HSC / Degree / Honours / Bachelors / Masters). */
export async function GET() {
  const session = await requireCampusInstitution();
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const programs = await prisma.cuProgram.findMany({
    where: { institutionId: session.institutionId },
    orderBy: [{ name: "asc" }],
    include: { _count: { select: { terms: true, courses: true, students: true, exams: true } } },
  });
  return NextResponse.json({ programs });
}

/** Create a program: { name, nameBn?, code, degreeLevel?, faculty?, department?,
    durationYears?, totalCredits?, gradeScale? ("GPA4" | "GPA5"), note? } */
export async function POST(req: Request) {
  const session = await requireCampusInstitution();
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const body = await req.json();
    const name = String(body.name ?? "").trim();
    const code = String(body.code ?? "").trim();
    if (!name || !code) {
      return NextResponse.json({ error: "Missing fields" }, { status: 400 });
    }

    const exists = await prisma.cuProgram.findFirst({
      where: { institutionId: session.institutionId, code },
      select: { id: true },
    });
    if (exists) return NextResponse.json({ error: "CODE_EXISTS" }, { status: 409 });

    const num = (v: unknown, fallback: number) => {
      const n = Number(v);
      return Number.isFinite(n) && n >= 0 ? n : fallback;
    };

    const program = await prisma.cuProgram.create({
      data: {
        institutionId: session.institutionId,
        name,
        nameBn: String(body.nameBn ?? "").trim() || null,
        code,
        degreeLevel: String(body.degreeLevel ?? "BACHELORS"),
        faculty: String(body.faculty ?? "").trim() || null,
        department: String(body.department ?? "").trim() || null,
        durationYears: Math.round(num(body.durationYears, 4)) || 4,
        totalCredits: num(body.totalCredits, 0),
        gradeScale: body.gradeScale === "GPA5" ? "GPA5" : "GPA4",
        note: String(body.note ?? "").trim() || null,
      },
    });
    return NextResponse.json({ program });
  } catch {
    return NextResponse.json({ error: "Could not create program" }, { status: 500 });
  }
}
