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

export const runtime = "nodejs";

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

// POST /api/companies/[id]/financials — upsert a company's marketing financials
// for one month (Manager-tier). Powers the executive dashboard metrics.
export const POST = withGuard(async (req: Request, ctx: Ctx) => {
  await requirePermission("financials:write");
  const { id } = await ctx.params;
  const data = await parseBody(req, companyFinancialsSchema);

  const company = await prisma.company.findUnique({ where: { id } });
  if (!company) throw new HttpError(404, "Company not found");

  const fields = {
    budget: data.budget ?? 0,
    adSpend: data.adSpend ?? 0,
    revenue: data.revenue ?? 0,
    leads: data.leads ?? 0,
    trials: data.trials ?? 0,
    enrollments: data.enrollments ?? 0,
  };

  const row = await prisma.companyMonthlyFinancials.upsert({
    where: {
      companyId_year_month: { companyId: id, year: data.year, month: data.month },
    },
    create: { companyId: id, year: data.year, month: data.month, ...fields },
    update: fields,
  });
  return ok(row);
});
