import { NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { patchCaptureRow } from "@/lib/capture";

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:
    | {
        objectiveIndicator?: string | null;
        quantityQuality?: string | null;
        compliance?: string | null;
        dueCommitment?: string | null;
        captureNote?: string | null;
        ownerUserId?: string | null;
        captureMode?: "manual" | "auto" | "hybrid";
        automationSource?: string | null;
        freshnessSlaHours?: number;
      }
    | undefined;

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

  try {
    const result = await patchCaptureRow({
      rowId: context.params.id,
      viewer: {
        userId: session.user.id,
        role: session.user.role,
        department: session.user.department ?? null,
      },
      payload: payload ?? {},
    });

    return NextResponse.json(result);
  } catch (error) {
    const message = error instanceof Error ? error.message : "Unable to patch capture row.";
    if (message === "Forbidden") {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 });
    }

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

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