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

export const runtime = "nodejs";

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

// POST /api/kpis/[id]/monthly — set (upsert) a KPI's target & actual for one
// calendar month (Manager-tier and above). Used for monthly KPI tracking.
export const POST = withGuard(async (req: Request, ctx: Ctx) => {
  await requirePermission("kpis:write");
  const { id } = await ctx.params;
  const data = await parseBody(req, kpiMonthlyValueSchema);

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

  const value = await prisma.kpiMonthlyValue.upsert({
    where: {
      kpiIndicatorId_year_month: { kpiIndicatorId: id, year: data.year, month: data.month },
    },
    create: {
      kpiIndicatorId: id,
      year: data.year,
      month: data.month,
      targetValue: data.targetValue ?? null,
      actualValue: data.actualValue ?? 0,
      note: data.note ?? null,
    },
    update: {
      targetValue: data.targetValue ?? null,
      actualValue: data.actualValue ?? 0,
      note: data.note ?? null,
    },
  });
  return ok(value);
});
