import { NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { patchWeeklyKpiRow } from "@/lib/kpis/persistence";
import type { WeeklyKpiPatchPayload } from "@/lib/kpis/types";

export async function PATCH(request: Request, context: { params: { id: string } }) {
  const session = await getServerSession(authOptions);
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  let payload: WeeklyKpiPatchPayload;
  try {
    payload = (await request.json()) as WeeklyKpiPatchPayload;
  } catch {
    return NextResponse.json({ error: "Invalid JSON body." }, { status: 400 });
  }

  try {
    const row = await patchWeeklyKpiRow(context.params.id, payload, {
      role: session.user.role,
      department: session.user.department ?? null,
    });

    return NextResponse.json({ ok: true, row });
  } catch (error) {
    const message = error instanceof Error ? error.message : "Unable to update KPI row.";
    if (message === "Forbidden" || message === "Only owner can modify core weekly KPI definitions.") {
      return NextResponse.json({ error: message }, { status: 403 });
    }

    if (message.includes("not found")) {
      return NextResponse.json({ error: message }, { status: 404 });
    }

    return NextResponse.json({ error: message }, { status: 400 });
  }
}
