import { setVerifyAck } from "@/lib/bulkUpload/server";
import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { AuthOptions } from "@/app/api/auth/[...nextauth]/authOptions";

// Records the "Verify classification" acknowledgement (ADR-0004 Step 1). No
// body — the per-row corrections go through the classifications PATCH; this just
// marks that the user has checked the sample and unlocks Finalise.
export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ portfolioId: string; uploadId: string }> }
) {
  const session = await getServerSession(AuthOptions);
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { uploadId } = await params;

  try {
    const result = await setVerifyAck(uploadId);
    switch (result.kind) {
      case "ok":
        return NextResponse.json(result.upload, { status: 200 });
      case "not_found":
        return NextResponse.json({ error: "Not found" }, { status: 404 });
      case "wrong_state":
        return NextResponse.json(
          { error: `Cannot verify classification in state '${result.current}'` },
          { status: 409 }
        );
    }
  } catch (error) {
    console.error("Failed to record classification verification:", error);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
