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

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

export async function PUT(req: Request, { params }: Params) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const { id } = await params;
  try {
    const body = await req.json();
    const name = String(body.name ?? "").trim();
    if (!name) return NextResponse.json({ error: "Name required" }, { status: 400 });
    const head = await prisma.feeHead.updateMany({
      where: { id: Number(id), institutionId: session.institutionId },
      data: {
        name,
        nameBn: String(body.nameBn ?? "").trim() || null,
        type: ["ADMISSION", "TUITION", "EXAM", "OTHER"].includes(body.type) ? body.type : undefined,
        defaultAmount: body.defaultAmount !== undefined ? Number(body.defaultAmount) : undefined,
        isActive: body.isActive !== undefined ? Boolean(body.isActive) : undefined,
      },
    });
    if (head.count === 0) return NextResponse.json({ error: "Not found" }, { status: 404 });
    return NextResponse.json({ success: true });
  } catch {
    return NextResponse.json({ error: "Could not update" }, { status: 500 });
  }
}

export async function DELETE(_req: Request, { params }: Params) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const { id } = await params;
  const used = await prisma.feeSchedule.count({
    where: { feeHeadId: Number(id), institutionId: session.institutionId },
  });
  if (used > 0) return NextResponse.json({ error: "IN_USE" }, { status: 409 });
  const res = await prisma.feeHead.deleteMany({
    where: { id: Number(id), institutionId: session.institutionId },
  });
  if (res.count === 0) return NextResponse.json({ error: "Not found" }, { status: 404 });
  return NextResponse.json({ success: true });
}
