import { beforeEach, describe, expect, it, vi } from "vitest";

const { mockBuildForwardHeaders } = vi.hoisted(() => ({
  mockBuildForwardHeaders: vi.fn(async () => new Headers({ "x-forwarded-for": "127.0.0.1" })),
}));

vi.mock("@/lib/runtime-config", () => ({
  getMnoteRuntimeConfig: () => ({ backendUrl: "http://backend.test" }),
}));

vi.mock("@/lib/server/forward-headers", () => ({
  buildForwardHeaders: mockBuildForwardHeaders,
}));

import { startDocumentAiOrchestratorRun } from "./document-ai-orchestrator";

describe("startDocumentAiOrchestratorRun", () => {
  beforeEach(() => {
    vi.restoreAllMocks();
    mockBuildForwardHeaders.mockClear();
    delete process.env.BACKEND_URL;
    delete process.env.BACKEND_INTERNAL_URL;
    delete process.env.MNOTE_AI_ORCHESTRATOR_API_KEY;
  });

  it("应把 leptos-tiptap 的 block 级 AI 上下文透传给 sidecar", async () => {
    const fetchMock = vi.fn(async () =>
      new Response('event: ready\ndata: {"ok":true}\n\n', {
        headers: { "Content-Type": "text/event-stream; charset=utf-8" },
      }),
    );
    vi.stubGlobal("fetch", fetchMock);

    await startDocumentAiOrchestratorRun({
      userId: "user-1",
      payload: {
        maxSteps: 8,
        messages: [{ role: "user", content: "改写当前块" }],
        context: {
          source: "leptos-tiptap-island",
          action: "ask_ai",
          documentId: "doc-1",
          workspaceId: "ws-1",
          selectedBlockId: "block-1",
          selectedUids: ["block-1"],
          selectedText: "旧段落",
          selection: { currentBlockId: "block-1", state: { from: 1, to: 4 } },
          tiptapDocument: { type: "doc", content: [{ type: "paragraph" }] },
          documentBlocks: { type: "doc", content: [{ type: "paragraph" }] },
        },
        options: {
          ai: {
            modelKey: "gpt-5.3-codex",
            profileId: "page_writer_polish",
            sessionId: "doc_ai:doc-1:session-1",
          },
        },
      },
    });

    expect(fetchMock).toHaveBeenCalledWith(
      "http://backend.test/api/v1/ai-agent/document/run",
      expect.objectContaining({ method: "POST" }),
    );
    const body = JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body));
    expect(body.context).toMatchObject({
      source: "leptos-tiptap-island",
      action: "ask_ai",
      documentId: "doc-1",
      workspaceId: "ws-1",
      selectedBlockId: "block-1",
      selectedUids: ["block-1"],
      selectedText: "旧段落",
      selection: { currentBlockId: "block-1", state: { from: 1, to: 4 } },
      tiptapDocument: { type: "doc", content: [{ type: "paragraph" }] },
      documentBlocks: { type: "doc", content: [{ type: "paragraph" }] },
    });
  });
});
