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

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

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

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