import { describe, expect, it, vi } from "vitest";
import { createDocServerTools } from "./docServerTools";

describe("createDocServerTools", () => {
  it("doc_insert_blocks 和 doc_replace_range 只操作快照，不直连 loadBlocks", async () => {
    const baseBlocks = [
      {
        id: "block_1",
        type: "paragraph",
        content: [{ type: "text", text: "hello" }],
        children: [],
      },
    ];

    const loadBlocks = vi.fn(async () => ({ blocks: baseBlocks, source: "client" }));
    const tools = createDocServerTools({
      ctx: { documentId: "doc_1", userId: "user_1", baseBlocks },
      allowedToolIds: new Set(["doc_insert_blocks", "doc_replace_range", "doc_get"]),
      loadBlocks,
    });

    const insertResult = await tools.run("doc_insert_blocks", {
      afterBlockId: "block_1",
      blocks: [{ type: "heading", text: "新标题", level: 2 }],
    });
    expect(insertResult.ok).toBe(true);
    expect(loadBlocks).not.toHaveBeenCalled();
    expect(Array.isArray((insertResult as any).data)).toBe(true);
    expect((insertResult as any).data).toHaveLength(2);

    const replaceResult = await tools.run("doc_replace_range", {
      blockId: "block_1",
      text: " world",
      mode: "append",
    });
    expect(replaceResult.ok).toBe(true);
    expect((replaceResult as any).data).toHaveLength(1);
    expect(((replaceResult as any).data[0] as any).content?.[0]?.text).toBe("helloworld");
  });
});
