import { prisma } from "@/lib/prisma";
import { requireUser, withGuard, HttpError } from "@/lib/guard";
import { ok } from "@/lib/http";
import { isManagerTier } from "@/lib/rbac";
import type { Prisma } from "@prisma/client";

export const runtime = "nodejs";

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

// DELETE /api/contributions/[id] — remove a contribution and roll its metric
// delta back out of BOTH the KPI's current value and the month's actual value
// (keeps aggregation consistent).
export const DELETE = withGuard(async (_req: Request, ctx: Ctx) => {
  const me = await requireUser();
  const { id } = await ctx.params;

  const log = await prisma.taskContributionLog.findUnique({
    where: { id },
    include: { task: true },
  });
  if (!log) throw new HttpError(404, "Contribution not found");
  if (!isManagerTier(me.role) && log.task.userId !== me.id) {
    throw new HttpError(403, "Forbidden");
  }

  const ops: Prisma.PrismaPromise<unknown>[] = [
    prisma.kpiIndicator.update({
      where: { id: log.kpiIndicatorId },
      data: { currentValue: { decrement: log.metricDelta } },
    }),
  ];
  // Legacy rows have no year/month; only reverse the monthly actual when known.
  if (log.year != null && log.month != null) {
    ops.push(
      prisma.kpiMonthlyValue.updateMany({
        where: { kpiIndicatorId: log.kpiIndicatorId, year: log.year, month: log.month },
        data: { actualValue: { decrement: log.metricDelta } },
      })
    );
  }
  ops.push(prisma.taskContributionLog.delete({ where: { id } }));

  await prisma.$transaction(ops);
  return ok({ ok: true });
});
