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,
  resolveRustBridgeCommandPlan,
  resolveRustBridgeQueryPlan,
} from "@/lib/documents/rust-runtime";

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

export async function GET(
  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 = buildDocumentQueryEnvelope({
        name: "mindmaps.get",
        payload: {
          documentId: docId,
          mindmapId,
          workspaceId: null,
        },
      });
      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,
      });
      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 } = (await request.json().catch(() => ({ data: null }))) as {
      data?: unknown;
      createOnly?: boolean;
    };

    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.put",
        payload: {
          documentId: docId,
          mindmapId,
          data: data ?? defaultMindmapData,
          createOnly: typeof createOnly === "boolean" ? createOnly : false,
        },
        context,
        target: {
          workspaceId: null,
          pageId: docId,
          blockId: mindmapId,
        },
        reason: "mindmap-route:put",
        refs: ["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,
      });
      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,
      });
      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,
      });
      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 });
}
