import { setColumnMapping } from "@/lib/bulkUpload/server";
import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";

const PatchSchema = z.object({
  columnMapping: z.record(z.string(), z.string()),
});

export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ portfolioId: string; uploadId: string }> }
) {
  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 setColumnMapping(uploadId, body.columnMapping);
    switch (result.kind) {
      case "ok":
        return NextResponse.json(result.upload, { status: 200 });
      case "not_found":
        return NextResponse.json({ error: "Not found" }, { status: 404 });
      case "invalid_status":
        return NextResponse.json(
          { error: `Cannot remap upload in state '${result.current}'` },
          { status: 409 }
        );
      case "invalid_mapping":
        return NextResponse.json({ error: result.reason }, { status: 422 });
    }
  } catch (error) {
    console.error("Failed to save column mapping:", error);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
