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("SUPER_ADMIN");
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { id } = await params;
  try {
    const body = await req.json();
    const name = String(body.name ?? "").trim();
    const nameBn = String(body.nameBn ?? "").trim() || name;
    const isActive = Boolean(body.isActive);

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

    const existing = await prisma.academicItem.findUnique({ where: { id: Number(id) } });
    if (!existing) return NextResponse.json({ error: "Not found" }, { status: 404 });

    const item = await prisma.academicItem.update({
      where: { id: existing.id },
      data: {
        name,
        nameBn,
        code: body.code !== undefined ? String(body.code).trim() || null : existing.code,
        isActive,
        institutionId:
          body.institutionId !== undefined
            ? body.institutionId
              ? Number(body.institutionId)
              : null
            : existing.institutionId,
      },
    });
    return NextResponse.json({ item });
  } catch {
    return NextResponse.json({ error: "Could not update item" }, { status: 500 });
  }
}

export async function DELETE(_req: Request, { params }: Params) {
  const session = await requireRole("SUPER_ADMIN");
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { id } = await params;
  try {
    await prisma.academicItem.delete({ where: { id: Number(id) } });
    return NextResponse.json({ success: true });
  } catch {
    return NextResponse.json({ error: "Could not delete item" }, { status: 500 });
  }
}
