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

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

// GET /api/departments — list departments (any signed-in user, for KPI/staff
// grouping and selectors).
export const GET = withGuard(async () => {
  await requireUser();
  const departments = await prisma.department.findMany({ orderBy: { name: "asc" } });
  return ok(departments);
});

// POST /api/departments — create a department (Manager-tier and above).
export const POST = withGuard(async (req: Request) => {
  await requirePermission("departments:write");
  const data = await parseBody(req, departmentSchema);
  const name = data.name.trim();
  const exists = await prisma.department.findUnique({ where: { name } });
  if (exists) return ok({ error: "Department name already in use" }, 409);
  const department = await prisma.department.create({
    data: { name, active: data.active ?? true, spansAll: data.spansAll ?? false },
  });
  return ok(department, 201);
});
