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

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 result = await requestCombineRetrigger({
    uploadId,
    sessionToken: readSessionToken(request),
  });

  switch (result.kind) {
    case "triggered":
      return NextResponse.json(
        { taskId: result.taskId, subTaskId: result.subTaskId },
        { status: 200 }
      );
    case "already_combined":
      return NextResponse.json({ alreadyCombined: true }, { status: 200 });
    case "already_dispatched":
      // Lost the double-dispatch CAS (or the combiner is already running) — a
      // benign no-op; the client just keeps polling and sees `combining`.
      return NextResponse.json({ alreadyDispatched: true }, { status: 200 });
    case "not_found":
      return NextResponse.json({ error: "Not found" }, { status: 404 });
    case "missing_task":
      return NextResponse.json({ error: "Upload has no task" }, { status: 422 });
    case "trigger_failed":
      return NextResponse.json({ error: result.message }, { status: result.status });
  }
}
