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

export const runtime = "nodejs";

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

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

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