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

// Finalise is now asynchronous (ADR-0005). This route no longer inserts
// properties; it dispatches the bulk_upload_finaliser Lambda and flips the
// BulkUpload to `finalising` via a compare-and-swap (the double-dispatch guard).
// The Lambda reads the combiner output, inserts the property rows, and writes the
// terminal `complete`/`failed` status directly. The user sees "Uploading to ARA"
// while the row is `finalising`; the onboarding surface polls for the outcome.
export async function POST(
  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;
  const sessionToken = readSessionToken(request);

  const result = await dispatchFinaliser({ uploadId, sessionToken });

  switch (result.kind) {
    case "ok":
      // Accepted: the finaliser is running; the row is now `finalising`.
      return NextResponse.json({ taskId: result.taskId }, { status: 202 });
    case "not_found":
      return NextResponse.json({ error: "Not found" }, { status: 404 });
    case "already_finalized":
      // Idempotent: nothing to do.
      return new NextResponse(null, { status: 200 });
    case "not_yet_combined":
      return NextResponse.json({ error: "Combiner not finished" }, { status: 409 });
    case "missing_task":
      return NextResponse.json({ error: "Upload has no task to finalise" }, { status: 409 });
    case "unresolved_addresses":
      return NextResponse.json(
        {
          error: `${result.count} address${result.count === 1 ? "" : "es"} still need a UPRN. Resolve them on the Addresses tab before finalising.`,
          unresolvedAddresses: result.count,
        },
        { status: 409 },
      );
    case "wrong_state":
      return NextResponse.json(
        { error: `Upload not ready to finalize (state: ${result.current})` },
        { status: 409 }
      );
    case "trigger_failed":
      return NextResponse.json({ error: result.message }, { status: result.status });
  }
}
