import { NextResponse } from "next/server";
import { isConvexEnabled } from "@/lib/convex/enabled";
import { getAuthedConvexClient } from "@/lib/convex/route";
import { fetchDocumentAiOrchestratorConfig } from "@/lib/server/document-ai-orchestrator";

export const dynamic = "force-dynamic";

export async function GET(request: Request) {
  let userId = "";
  if (isConvexEnabled()) {
    const { auth } = await getAuthedConvexClient();
    userId = auth.userId ?? "";
  }
  if (!userId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const payload = await fetchDocumentAiOrchestratorConfig({ request });
    return NextResponse.json(payload, {
      headers: {
        "Cache-Control": "no-store",
      },
    });
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
