import { NextResponse } from "next/server";
import { isConvexEnabled } from "@/lib/convex/enabled";
import { getAuthedConvexClient } from "@/lib/convex/route";
import {
  buildDocumentBridgeContext,
  buildDocumentQueryEnvelope,
  documentBridgeErrorResponse,
} from "@/lib/documents/bridge";
import {
  executeRustBridgeQueryTransport,
  resolveRustBridgeQueryPlan,
} from "@/lib/documents/rust-runtime";
import type { SidebarDatasetListQueryResult } from "@/lib/sidebar-data";
import { resolveKernelFileTreeProjection } from "@/lib/server/kernel-file-tree";

export const dynamic = "force-dynamic";
export const runtime = "nodejs";

function readNumberParam(url: URL, name: string): number | null {
  const raw = url.searchParams.get(name);
  if (!raw?.trim()) {
    return null;
  }
  const parsed = Number(raw);
  return Number.isFinite(parsed) ? parsed : null;
}

export async function GET(request: Request) {
  if (!isConvexEnabled()) {
    return NextResponse.json({ error: "当前仅支持 Convex 模式" }, { status: 501 });
  }

  const url = new URL(request.url);
  const workspaceId = url.searchParams.get("workspaceId")?.trim();
  if (!workspaceId) {
    return NextResponse.json({ error: "缺少 workspaceId" }, { status: 400 });
  }

  try {
    const { auth, client } = await getAuthedConvexClient();
    const context = await buildDocumentBridgeContext({
      request,
      workspaceId,
    });
    const envelope = buildDocumentQueryEnvelope({
      name: "sidebar.dataset.list",
      payload: {
        workspaceId,
      },
    });
    const plan = await resolveRustBridgeQueryPlan({
      context,
      envelope,
    });
    const dataset = await executeRustBridgeQueryTransport<SidebarDatasetListQueryResult>({
      client,
      plan,
    });
    const projection = await resolveKernelFileTreeProjection({
      client,
      request,
      workspaceId,
      actor: {
        actorType: "user",
        actorId: auth.userId,
        sessionId: null,
      },
      dataset,
      rootNodeId: url.searchParams.get("rootNodeId")?.trim() || null,
      depth: readNumberParam(url, "depth"),
      query: url.searchParams.get("query")?.trim() || null,
      maxResults: readNumberParam(url, "maxResults"),
    });

    return NextResponse.json({
      ok: true,
      requestId: context.requestId,
      traceId: context.traceId,
      result: projection,
    });
  } catch (error) {
    return documentBridgeErrorResponse(error);
  }
}
