import { NextResponse } from "next/server";
import { isConvexEnabled } from "@/lib/convex/enabled";
import { getAuthedConvexClient } from "@/lib/convex/route";
import { buildMindmapRouteMeta } from "@/lib/mindmap/mindmapRouteMeta";
import {
  buildDocumentBridgeContextWithActor,
  buildDocumentCommandEnvelope,
  buildDocumentQueryEnvelope,
  documentBridgeErrorResponse,
} from "@/lib/documents/bridge";
import {
  executeRustBridgeMutationTransport,
  executeRustBridgeQueryTransport,
  recordRustBridgeCommandArtifacts,
  resolveRustBridgeCommandPlan,
  resolveRustBridgeQueryPlan,
} from "@/lib/documents/rust-runtime";
import {
  applyMetadataOnlyMindmapCommands,
  isMetadataOnlyMindmapCommandSet,
} from "@/lib/mindmap/mindmap-command-apply-local";

const defaultMindmapData = {
  data: { text: "中心主题" },
  children: [],
};

async function recordMindmapCommandSuccess(args: {
  context: ReturnType<typeof buildDocumentBridgeContextWithActor>;
  envelope: ReturnType<typeof buildDocumentCommandEnvelope>;
  client: Awaited<ReturnType<typeof getAuthedConvexClient>>["client"];
  plan: Awaited<ReturnType<typeof resolveRustBridgeCommandPlan>>;
  result: unknown;
}) {
  try {
    await recordRustBridgeCommandArtifacts(args);
  } catch (error) {
    console.warn("[mindmap-route] Rust bridge success artifacts skipped:", error);
  }
}

export async function GET(
  request: Request,
  { params }: { params: Promise<{ docId: string; mindmapId: string }> },
) {
  const { docId, mindmapId } = await params;
  const url = new URL(request.url);
  const view = url.searchParams.get("view");
  const queryName =
    view === "simple_mind_map_scene" || url.searchParams.get("queryName") === "mindmap.simple_mind_map_scene.get"
      ? "mindmap.simple_mind_map_scene.get"
      : view === "editor_scene"
        ? "mindmap.editor_scene.get"
        : "mindmaps.get";

  if (isConvexEnabled()) {
    const { auth, client } = await getAuthedConvexClient();
    try {
      const context = buildDocumentBridgeContextWithActor({
        request,
        actor: {
          actorType: "user",
          actorId: auth.userId,
          sessionId: null,
        },
        workspaceId: null,
        source: {
          channel: "mindmap-route",
          client: "wolai-frontend",
        },
      });
      const envelope = buildDocumentQueryEnvelope({
        name: queryName,
        payload: {
          documentId: docId,
          mindmapId,
          workspaceId: null,
          rootNodeId: url.searchParams.get("rootNodeId"),
        },
      });
      const plan = await resolveRustBridgeQueryPlan({ context, envelope });
      const res = await executeRustBridgeQueryTransport<{
        ok?: boolean;
        data?: unknown;
        meta?: {
          workspace_id?: string | null;
          exists?: boolean;
          deleted_at?: string | null;
          created_at?: string | null;
          updated_at?: string | null;
        } | null;
      }>({
        client,
        plan,
      });
      if (queryName === "mindmap.simple_mind_map_scene.get" || queryName === "mindmap.editor_scene.get") {
        return NextResponse.json(res);
      }
      return NextResponse.json({
        data: res?.data ?? defaultMindmapData,
        source: "convex",
        meta: {
          ...buildMindmapRouteMeta(request, {
            workspaceId: res?.meta?.workspace_id ?? null,
            documentId: docId,
            mindmapId,
            ownerUserId: auth.userId,
          }),
          exists: Boolean(res?.meta?.exists),
          deletedAt: res?.meta?.deleted_at ?? null,
          createdAt: res?.meta?.created_at ?? null,
          updatedAt: res?.meta?.updated_at ?? null,
        },
      });
    } catch (error) {
      return documentBridgeErrorResponse(error);
    }
  }

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

export async function POST(
  request: Request,
  { params }: { params: Promise<{ docId: string; mindmapId: string }> },
) {
  const { docId, mindmapId } = await params;

  if (isConvexEnabled()) {
    const { auth, client } = await getAuthedConvexClient();
    const { data, createOnly, commandName, commands, projectionRevision } = (await request.json().catch(() => ({ data: null }))) as {
      data?: unknown;
      createOnly?: boolean;
      commandName?: string;
      commands?: unknown[];
      projectionRevision?: number | null;
    };

    try {
      const context = buildDocumentBridgeContextWithActor({
        request,
        actor: {
          actorType: "user",
          actorId: auth.userId,
          sessionId: null,
        },
        workspaceId: null,
        source: {
          channel: "mindmap-route",
          client: "wolai-frontend",
        },
      });
      const isCommandApply = commandName === "mindmap.command.apply";
      const isMetadataOnlyCommandApply = isCommandApply && isMetadataOnlyMindmapCommandSet(Array.isArray(commands) ? commands : []);
      if (isMetadataOnlyCommandApply) {
        const currentEnvelope = buildDocumentQueryEnvelope({
          name: "mindmaps.get",
          payload: {
            documentId: docId,
            mindmapId,
            workspaceId: null,
          },
        });
        const currentPlan = await resolveRustBridgeQueryPlan({ context, envelope: currentEnvelope });
        const currentResult = await executeRustBridgeQueryTransport<{ data?: unknown }>({
          client,
          plan: currentPlan,
        });
        const applied = applyMetadataOnlyMindmapCommands(currentResult?.data ?? defaultMindmapData, commands);
        if (applied.errors.length > 0) {
          return NextResponse.json(
            {
              error: "mindmap_command_apply_failed",
              details: applied.errors,
            },
            { status: 400 },
          );
        }
        const putEnvelope = buildDocumentCommandEnvelope({
          name: "mindmaps.put",
          payload: {
            documentId: docId,
            mindmapId,
            data: applied.data,
            createOnly: false,
          },
          context,
          target: {
            workspaceId: null,
            pageId: docId,
            blockId: mindmapId,
          },
          reason: "mindmap-route:command-apply-metadata-fallback",
          refs: ["task-166", "mindmap-command-bridge", "mindmap-metadata-fallback"],
        });
        const putPlan = await resolveRustBridgeCommandPlan({ context, envelope: putEnvelope });
        const result = await executeRustBridgeMutationTransport<{
          ok?: boolean;
          workspace_id?: string | null;
          updated_at?: string | null;
        }>({
          client,
          plan: putPlan,
        });
        await recordMindmapCommandSuccess({
          context,
          envelope: putEnvelope,
          client,
          plan: putPlan,
          result,
        });
        return NextResponse.json({
          ...(result ?? { ok: true }),
          commandName: "mindmap.command.apply",
          applied: applied.applied,
          errors: applied.errors,
          projectionRevision: typeof projectionRevision === "number" ? projectionRevision : null,
          meta: {
            ...buildMindmapRouteMeta(request, {
              workspaceId: result?.workspace_id ?? null,
              documentId: docId,
              mindmapId,
              ownerUserId: auth.userId,
            }),
            updatedAt: result?.updated_at ?? null,
          },
        });
      }
      const envelope = buildDocumentCommandEnvelope({
        name: isCommandApply ? "mindmap.command.apply" : "mindmaps.put",
        payload: isCommandApply
          ? {
              documentId: docId,
              mindmapId,
              workspaceId: null,
              commands: Array.isArray(commands) ? commands : [],
              projectionRevision: typeof projectionRevision === "number" ? projectionRevision : null,
            }
          : {
              documentId: docId,
              mindmapId,
              data: data ?? defaultMindmapData,
              createOnly: typeof createOnly === "boolean" ? createOnly : false,
            },
        context,
        target: {
          workspaceId: null,
          pageId: docId,
          blockId: mindmapId,
        },
        reason: isCommandApply ? "mindmap-route:command-apply" : "mindmap-route:put",
        refs: isCommandApply ? ["task-166", "mindmap-command-bridge"] : ["task-032", "mindmap-route"],
      });
      const plan = await resolveRustBridgeCommandPlan({ context, envelope });
      const result = await executeRustBridgeMutationTransport<{
        ok?: boolean;
        workspace_id?: string | null;
        updated_at?: string | null;
      }>({
        client,
        plan,
      });
      await recordMindmapCommandSuccess({
        context,
        envelope,
        client,
        plan,
        result,
      });
      return NextResponse.json({
        ...(result ?? { ok: true }),
        meta: {
          ...buildMindmapRouteMeta(request, {
            workspaceId: result?.workspace_id ?? null,
            documentId: docId,
            mindmapId,
            ownerUserId: auth.userId,
          }),
          updatedAt: result?.updated_at ?? null,
        },
      });
    } catch (error) {
      return documentBridgeErrorResponse(error);
    }
  }

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

export async function DELETE(
  request: Request,
  { params }: { params: Promise<{ docId: string; mindmapId: string }> },
) {
  const { docId, mindmapId } = await params;

  if (isConvexEnabled()) {
    const { auth, client } = await getAuthedConvexClient();
    try {
      const context = buildDocumentBridgeContextWithActor({
        request,
        actor: {
          actorType: "user",
          actorId: auth.userId,
          sessionId: null,
        },
        workspaceId: null,
        source: {
          channel: "mindmap-route",
          client: "wolai-frontend",
        },
      });
      const envelope = buildDocumentCommandEnvelope({
        name: "mindmaps.delete",
        payload: {
          documentId: docId,
          mindmapId,
        },
        context,
        target: {
          workspaceId: null,
          pageId: docId,
          blockId: mindmapId,
        },
        reason: "mindmap-route:delete",
        refs: ["task-047", "mindmap-route"],
      });
      const plan = await resolveRustBridgeCommandPlan({ context, envelope });
      const result = await executeRustBridgeMutationTransport<{
        ok?: boolean;
        workspace_id?: string | null;
        deleted_at?: string | null;
      }>({
        client,
        plan,
      });
      await recordMindmapCommandSuccess({
        context,
        envelope,
        client,
        plan,
        result,
      });
      return NextResponse.json({
        ...(result ?? { ok: true }),
        meta: {
          ...buildMindmapRouteMeta(request, {
            workspaceId: result?.workspace_id ?? null,
            documentId: docId,
            mindmapId,
            ownerUserId: auth.userId,
          }),
          deletedAt: result?.deleted_at ?? null,
        },
      });
    } catch (error) {
      return documentBridgeErrorResponse(error);
    }
  }

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

export async function PATCH(
  request: Request,
  { params }: { params: Promise<{ docId: string; mindmapId: string }> },
) {
  const { docId, mindmapId } = await params;

  if (isConvexEnabled()) {
    const { auth, client } = await getAuthedConvexClient();
    const { action } = (await request.json().catch(() => ({}))) as { action?: string };
    if (action !== "restore" && action !== "purge") {
      return NextResponse.json({ error: "不支持的操作" }, { status: 400 });
    }

    try {
      const context = buildDocumentBridgeContextWithActor({
        request,
        actor: {
          actorType: "user",
          actorId: auth.userId,
          sessionId: null,
        },
        workspaceId: null,
        source: {
          channel: "mindmap-route",
          client: "wolai-frontend",
        },
      });
      const envelope = buildDocumentCommandEnvelope({
        name: action === "purge" ? "mindmaps.purge" : "mindmaps.restore",
        payload: {
          documentId: docId,
          mindmapId,
        },
        context,
        target: {
          workspaceId: null,
          pageId: docId,
          blockId: mindmapId,
        },
        reason: `mindmap-route:${action}`,
        refs: ["task-047", "mindmap-route"],
      });
      const plan = await resolveRustBridgeCommandPlan({ context, envelope });
      const result = await executeRustBridgeMutationTransport<{
        ok?: boolean;
        workspace_id?: string | null;
        updated_at?: string | null;
      }>({
        client,
        plan,
      });
      await recordMindmapCommandSuccess({
        context,
        envelope,
        client,
        plan,
        result,
      });
      return NextResponse.json({
        ...(result ?? { ok: true }),
        meta: {
          ...buildMindmapRouteMeta(request, {
            workspaceId: result?.workspace_id ?? null,
            documentId: docId,
            mindmapId,
            ownerUserId: auth.userId,
          }),
          updatedAt: action === "restore" ? result?.updated_at ?? null : null,
        },
      });
    } catch (error) {
      return documentBridgeErrorResponse(error);
    }
  }

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