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

const PatchSchema = z.object({
  // entry-count -> permutation (part slot -> file position). See ADR-0004.
  permutations: z.record(z.string(), z.array(z.number().int().nonnegative())),
});

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;

  let body;
  try {
    body = PatchSchema.parse(await request.json());
  } catch {
    return NextResponse.json({ error: "Invalid input" }, { status: 400 });
  }

  try {
    const result = await setMultiEntryOrdering(uploadId, body.permutations);
    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 set ordering in state '${result.current}'` },
          { status: 409 }
        );
      case "not_multi_entry":
        return NextResponse.json({ error: "Upload has no multi-entry rows" }, { status: 409 });
      case "invalid_ordering":
        return NextResponse.json({ error: result.reason }, { status: 422 });
    }
  } catch (error) {
    console.error("Failed to save multi-entry ordering:", error);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
