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

const FEE_TYPES = ["ADMISSION", "TUITION", "EXAM", "OTHER"];

export async function GET() {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const heads = await prisma.feeHead.findMany({
    where: { institutionId: session.institutionId },
    orderBy: { id: "asc" },
    include: { _count: { select: { schedules: true } } },
  });
  return NextResponse.json({ heads });
}

export async function POST(req: Request) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const body = await req.json();
    const name = String(body.name ?? "").trim();
    const type = FEE_TYPES.includes(body.type) ? body.type : "TUITION";
    const defaultAmount = Number(body.defaultAmount) || 0;

    if (!name) return NextResponse.json({ error: "Name required" }, { status: 400 });

    const head = await prisma.feeHead.create({
      data: {
        institutionId: session.institutionId,
        name,
        nameBn: String(body.nameBn ?? "").trim() || null,
        type: type as never,
        defaultAmount,
      },
    });
    return NextResponse.json({ head });
  } catch {
    return NextResponse.json({ error: "Could not create fee head" }, { status: 500 });
  }
}
