import { prisma } from "@/lib/prisma";
import { requirePermission, withGuard, HttpError } from "@/lib/guard";
import { parseBody, ok } from "@/lib/http";
import { departmentSchema } from "@/lib/validators";

export const runtime = "nodejs";

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

// PATCH /api/departments/[id] — rename / (de)activate (Manager-tier and above).
export const PATCH = withGuard(async (req: Request, ctx: Ctx) => {
  await requirePermission("departments:write");
  const { id } = await ctx.params;
  const data = await parseBody(req, departmentSchema.partial());
  const department = await prisma.department
    .update({
      where: { id },
      data: {
        ...(data.name !== undefined && { name: data.name.trim() }),
        ...(data.active !== undefined && { active: data.active }),
        ...(data.spansAll !== undefined && { spansAll: data.spansAll }),
      },
    })
    .catch(() => {
      throw new HttpError(404, "Department not found");
    });
  return ok(department);
});

// DELETE /api/departments/[id] — remove a department. Linked KPIs and users
// keep their data but lose the department tag (onDelete: SetNull).
export const DELETE = withGuard(async (_req: Request, ctx: Ctx) => {
  await requirePermission("departments:write");
  const { id } = await ctx.params;
  await prisma.department.delete({ where: { id } }).catch(() => {
    throw new HttpError(404, "Department not found");
  });
  return ok({ ok: true });
});
