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

// GET — status of a triggered bulk download, for in-app polling. Reads the
// worker's sub_task.outputs (presigned URL, included count, skipped list).
export async function GET(
  _request: NextRequest,
  props: { params: Promise<{ portfolioId: string; taskId: string }> },
) {
  const session = await getServerSession(AuthOptions);
  if (!session?.user?.email) {
    return NextResponse.json({ error: "Unauthorised" }, { status: 401 });
  }
  const { portfolioId, taskId } = await props.params;
  if (!/^\d+$/.test(portfolioId)) {
    return NextResponse.json({ error: "Invalid portfolio id" }, { status: 400 });
  }

  try {
    const status = await getBulkDownloadStatus(portfolioId, taskId);
    if (!status) {
      return NextResponse.json({ error: "Not found" }, { status: 404 });
    }
    return NextResponse.json(status);
  } catch (err) {
    console.error("GET /bulk-document-download/[taskId] error:", err);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
