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

export const runtime = "nodejs";

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

// PATCH /api/kpis/[id] — edit an indicator (Manager-tier and above).
export const PATCH = withGuard(async (req: Request, ctx: Ctx) => {
  await requirePermission("kpis:write");
  const { id } = await ctx.params;
  const data = await parseBody(req, kpiUpdateSchema);

  const kpi = await prisma.kpiIndicator
    .update({
      where: { id },
      data: {
        ...(data.name !== undefined && { name: data.name }),
        ...(data.description !== undefined && { description: data.description || null }),
        ...(data.targetValue !== undefined && { targetValue: data.targetValue }),
        ...(data.currentValue !== undefined && { currentValue: data.currentValue }),
        ...(data.unit !== undefined && { unit: data.unit }),
        ...(data.period !== undefined && { period: data.period }),
        ...(data.type !== undefined && { type: data.type }),
        ...(data.category !== undefined && { category: data.category }),
        ...(data.companyId !== undefined && { companyId: data.companyId || null }),
        ...(data.departmentId !== undefined && { departmentId: data.departmentId || null }),
        ...(data.assignedUserId !== undefined && {
          assignedUserId: data.assignedUserId || null,
        }),
        ...(data.assignedPosition !== undefined && {
          assignedPosition: data.assignedPosition || null,
        }),
        ...(data.weightage !== undefined && { weightage: data.weightage }),
        // Replace the full set of channels when provided.
        ...(data.channelIds !== undefined && {
          channels: { set: data.channelIds.map((cid) => ({ id: cid })) },
        }),
      },
      include: {
        company: { select: { id: true, name: true } },
        department: { select: { id: true, name: true } },
        assignedUser: { select: { id: true, name: true, position: true } },
        channels: { select: { id: true, name: true } },
      },
    })
    .catch(() => {
      throw new HttpError(404, "KPI not found");
    });
  return ok(kpi);
});

// DELETE /api/kpis/[id] — remove an indicator (cascades its contribution logs).
export const DELETE = withGuard(async (_req: Request, ctx: Ctx) => {
  await requirePermission("kpis:write");
  const { id } = await ctx.params;
  await prisma.kpiIndicator.delete({ where: { id } }).catch(() => {
    throw new HttpError(404, "KPI not found");
  });
  return ok({ ok: true });
});
