import { headers } from "next/headers";
import { getAuthedConvexClient } from "@/lib/convex/route";
import { isConvexEnabled } from "@/lib/convex/enabled";
import { buildDocumentBridgeContext, buildDocumentQueryEnvelope } from "@/lib/documents/bridge";
import { executeRustBridgeQueryTransport, resolveRustBridgeQueryPlan } from "@/lib/documents/rust-runtime";
import {
  buildMindmapProjection,
  defaultMindmapData,
  type MindmapProjection,
} from "@/lib/mindmap/mindmap-projection";
import MindmapPageClient from "./mindmap-page-client";

type MindmapRouteQueryResult = {
  data?: unknown;
  meta?: unknown;
};

async function fetchMindmapProjectionOnServer(input: {
  docId: string;
  mindmapId: string;
}): Promise<MindmapProjection | null> {
  if (!isConvexEnabled()) {
    return buildMindmapProjection({
      documentId: input.docId,
      mindmapId: input.mindmapId,
      data: defaultMindmapData,
      meta: null,
    });
  }

  try {
    const headerList = await headers();
    const requestHeaders = new Headers();
    [
      "cookie",
      "authorization",
      "x-request-id",
      "x-trace-id",
      "x-session-id",
      "x-source-channel",
      "x-source-client",
      "user-agent",
    ].forEach((name) => {
      const value = headerList.get(name);
      if (value) {
        requestHeaders.set(name, value);
      }
    });

    const request = new Request("http://mnote.local/mindmap/projection", {
      method: "GET",
      headers: requestHeaders,
    });
    const { client } = await getAuthedConvexClient();
    const context = await buildDocumentBridgeContext({
      request,
      workspaceId: null,
    });
    const envelope = buildDocumentQueryEnvelope({
      name: "mindmaps.get",
      payload: {
        documentId: input.docId,
        mindmapId: input.mindmapId,
        workspaceId: null,
      },
    });
    const plan = await resolveRustBridgeQueryPlan({
      context,
      envelope,
    });
    const result = await executeRustBridgeQueryTransport<MindmapRouteQueryResult | null>({
      client,
      plan,
    });

    return buildMindmapProjection({
      documentId: input.docId,
      mindmapId: input.mindmapId,
      data: result?.data ?? defaultMindmapData,
      meta: result?.meta ?? {
        requestId: context.requestId,
        traceId: context.traceId,
        workspaceId: context.workspaceId,
        documentId: input.docId,
        pageId: input.docId,
        mindmapId: input.mindmapId,
        attachmentId: input.mindmapId,
      },
    });
  } catch {
    return null;
  }
}

export default async function MindmapFullscreenPage({
  params,
}: {
  params: Promise<{ docId: string; mindmapId: string }>;
}) {
  const { docId, mindmapId } = await params;
  const initialProjection = await fetchMindmapProjectionOnServer({ docId, mindmapId });

  return (
    <MindmapPageClient
      docId={docId}
      mindmapId={mindmapId}
      initialProjection={initialProjection}
    />
  );
}
