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

export const dynamic = "force-dynamic";

export async function GET(request: Request) {
  if (isConvexEnabled()) {
    const { auth, client } = await getAuthedConvexClient();

    const url = new URL(request.url);
    const workspaceIdParam = url.searchParams.get("workspaceId");
    const bootstrap = await client.mutation(api.workspaces.ensureDefaultWorkspace, {
      fallbackName: auth.email ?? auth.name ?? "我的空间",
      workspaceIdIfCreate: randomUUID(),
    });
    const targetWorkspaceId = workspaceIdParam?.trim() || bootstrap.activeWorkspaceId || null;

    if (!targetWorkspaceId) {
      return NextResponse.json({ error: "暂无可用工作空间" }, { status: 404 });
    }

    try {
      const bridgeContext = await buildDocumentBridgeContext({
        request,
        workspaceId: targetWorkspaceId,
      });
      const envelope = buildDocumentQueryEnvelope({
        name: "sidebar.dataset.list",
        payload: {
          workspaceId: targetWorkspaceId,
        },
      });
      const plan = await resolveRustBridgeQueryPlan({
        context: bridgeContext,
        envelope,
      });
      const sidebarDataset = await executeRustBridgeQueryTransport<SidebarDatasetListQueryResult>({
        client,
        plan,
      });
      const sidebarDatasetWithFileTree = attachKernelFileTreeProjection({
        dataset: sidebarDataset,
        projection: await resolveKernelFileTreeProjection({
          client,
          request,
          workspaceId: targetWorkspaceId,
          actor: {
            actorType: "user",
            actorId: auth.userId,
            sessionId: null,
          },
          dataset: sidebarDataset,
        }),
      });
      const result = mapSidebarDatasetListQueryResultToInitialData(sidebarDatasetWithFileTree);

      return NextResponse.json({
        ...result,
        meta: {
          requestId: bridgeContext.requestId,
          traceId: bridgeContext.traceId,
          queryName: envelope.name,
        },
      });
    } catch (error) {
      return documentBridgeErrorResponse(error);
    }
  }

  return NextResponse.json({ error: "当前仅支持 Convex 模式" }, { status: 501 });

  /*
  const supabase = await createSupabaseRouteClient();
  const {
    data: { session },
  } = await supabase.auth.getSession();

  if (!session) {
    return NextResponse.json({ error: "未登录" }, { status: 401 });
  }

  const url = new URL(request.url);
  const workspaceIdParam = url.searchParams.get("workspaceId");

  await ensureDefaultWorkspace(supabase, session.user.id, session.user.email ?? "我的空间");
  const { workspaces, activeWorkspaceId } = await fetchWorkspaceSummaries(supabase, session.user.id);
  const targetWorkspaceId = workspaceIdParam || activeWorkspaceId;

  if (!targetWorkspaceId) {
    return NextResponse.json({ error: "暂无可用工作空间" }, { status: 404 });
  }

  try {
    const dataset = await fetchSidebarDataset(supabase, targetWorkspaceId);
    const docIds = dataset.documents.map((d) => d.id);
    const localMindmapFiles = await detectLocalMindmapFiles(docIds);
    const mindmapAssetChildren =
      await detectLocalMindmapImageAssetIdsByMindmapId(localMindmapFiles);
    const mindmapDocs = Array.from(new Set([...(dataset.mindmapDocs ?? []), ...(await detectLocalMindmapDocs(docIds))]));
    const trashedMindmapAssets = await detectLocalTrashedMindmapAssets(targetWorkspaceId, docIds);
    const docById = new Map(dataset.documents.map((d) => [d.id, d]));
    const mindmapAssets: MediaAsset[] = localMindmapFiles.map((item) => {       
      const doc = docById.get(item.documentId);
      const workspaceId = doc?.workspace_id ?? targetWorkspaceId;
      const fileUrlBase = item.source === "legacy" ? `/mindmaps/${item.documentId}` : `/documents/${item.documentId}`;
      return {
        id: item.mindmapId,
        workspace_id: workspaceId,
        document_id: item.documentId,
        asset_type: "mindmap",
        file_url: `${fileUrlBase}/${item.fileName}`,
        thumbnail_url: null,
        bucket: null,
        storage_path: null,
        file_name: item.fileName,
        file_size: null,
        mime_type: "application/json",
        ocr_payload: undefined,
        ocr_strategy: null,
        ocr_text: null,
        ocr_status: null,
        signed_url: null,
        created_at: "",
        updated_at: "",
      };
    });

    const tableAssets: MediaAsset[] = (dataset.tables ?? []).map((row) => {
      const base = (row.title ?? "未命名表格").trim() || "未命名表格";
      const fileName = base.toLowerCase().endsWith(".luckysheet") ? base : `${base}.luckysheet`;
      return {
        id: row.id,
        workspace_id: row.workspace_id ?? targetWorkspaceId,
        document_id: row.document_id,
        asset_type: "luckysheet",
        file_url: `/tables/${row.id}/view`,
        thumbnail_url: null,
        bucket: null,
        storage_path: null,
        file_name: fileName,
        file_size: null,
        mime_type: "application/json",
        ocr_payload: undefined,
        ocr_strategy: null,
        ocr_text: null,
        ocr_status: null,
        signed_url: null,
        created_at: row.created_at ?? "",
        updated_at: row.updated_at ?? "",
      };
    });

    const payload: SidebarInitialData = {
      activeWorkspaceId: targetWorkspaceId,
      workspaces,
      documents: dataset.documents,
      trashedDocuments: dataset.trashedDocuments,
      trashedMediaAssets: dataset.trashedMediaAssets ?? [],
      trashedMindmapAssets,
      mindmapDocs,
      mindmapAssets,
      mindmapAssetChildren,
      tableAssets,
      mediaAssets: dataset.mediaAssets ?? [],
    };

    return NextResponse.json(payload);
  } catch (error) {
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "拉取侧边栏数据失败" },
      { status: 500 },
    );
  }
  */
}
