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

vi.mock("@/lib/convex/enabled", () => ({
  isConvexEnabled: vi.fn(() => true),
}));

vi.mock("@/lib/auth/authContext", () => ({
  HttpError: class HttpError extends Error {
    status: number;

    constructor(status: number, message: string) {
      super(message);
      this.status = status;
    }
  },
  requireAuthContext: vi.fn(async () => ({
    userId: "user_1",
  })),
}));

vi.mock("@/lib/api-utils", () => ({
  apiErrorResponse: vi.fn((message: string, status = 500, details?: unknown) => ({
    message,
    status,
    details,
  })),
}));

vi.mock("@/lib/documents/page-command-adapter", () => ({
  executeDocumentCreateChildBridgeCommand: vi.fn(async () => new Response(JSON.stringify({ ok: true }))),
  executeDocumentTemplateBridgeCommand: vi.fn(async () => new Response(JSON.stringify({ ok: true }))),
  executeDocumentEmptyTrashBridgeCommand: vi.fn(async () => new Response(JSON.stringify({ ok: true }))),
}));

vi.mock("@/lib/documents/page-write-command-adapter", () => ({
  executePageWriteBridgeCommand: vi.fn(async () => ({
    requestId: "req_1",
    traceId: "trace_1",
    commandId: "cmd_1",
    commandName: "page.command",
    revision: 1,
    conflictDetectionKey: "doc_1:1",
  })),
}));

import { POST as postCreateChild } from "@/app/api/documents/create-child/route";
import { POST as postTemplate } from "@/app/api/documents/template/route";
import { POST as postEmptyTrash } from "@/app/api/documents/empty-trash/route";
import { POST as postTitle } from "@/app/api/documents/title/route";
import { POST as postOptions } from "@/app/api/documents/options/route";
import { POST as postSave } from "@/app/api/documents/save/route";
import {
  executeDocumentCreateChildBridgeCommand,
  executeDocumentTemplateBridgeCommand,
  executeDocumentEmptyTrashBridgeCommand,
} from "@/lib/documents/page-command-adapter";
import { executePageWriteBridgeCommand } from "@/lib/documents/page-write-command-adapter";

afterEach(() => {
  vi.restoreAllMocks();
  vi.clearAllMocks();
});

describe("documents route adapters", () => {
  it("title route 在缺少 page head commandName 时返回校验错误", async () => {
    const response = await postTitle(new Request("http://localhost/api/documents/title", {
      method: "POST",
      headers: {
        "content-type": "application/json",
      },
      body: JSON.stringify({ documentId: "doc_1", workspaceId: "ws_1", title: "新标题" }),
    })) as {
      message: string;
      status: number;
      details?: { code?: string; details?: Array<{ field: string; reason: string }> };
    };

    expect(response.status).toBe(400);
    expect(response.message).toBe("标题保存仅支持 page.head.updateTitle");
    expect(response.details).toEqual({
      code: "VALIDATION_ERROR",
      details: [{ field: "commandName", reason: "expected page.head.updateTitle" }],
    });
    expect(executePageWriteBridgeCommand).not.toHaveBeenCalled();
  });

  it("creates child route delegates to unified adapter", async () => {
    await postCreateChild(new Request("http://localhost/api/documents/create-child", {
      method: "POST",
      body: JSON.stringify({ parentId: null }),
    }));
    expect(executeDocumentCreateChildBridgeCommand).toHaveBeenCalled();
  });

  it("template route delegates to unified adapter", async () => {
    await postTemplate(new Request("http://localhost/api/documents/template", {
      method: "POST",
      body: JSON.stringify({ documentId: "doc_1", isTemplate: true }),
    }));
    expect(executeDocumentTemplateBridgeCommand).toHaveBeenCalled();
  });

  it("empty trash route delegates to unified adapter", async () => {
    await postEmptyTrash(new Request("http://localhost/api/documents/empty-trash", {
      method: "POST",
      body: JSON.stringify({ workspaceId: "ws_1" }),
    }));
    expect(executeDocumentEmptyTrashBridgeCommand).toHaveBeenCalled();
  });

  it("title route 在 page head 请求下仍委托 unified page write adapter", async () => {
    await postTitle(new Request("http://localhost/api/documents/title", {
      method: "POST",
      body: JSON.stringify({
        documentId: "doc_1",
        workspaceId: "ws_1",
        title: "新标题",
        commandName: "page.head.updateTitle",
      }),
    }));

    expect(executePageWriteBridgeCommand).toHaveBeenCalled();
  });

  it("options route delegates to unified page write adapter", async () => {
    await postOptions(new Request("http://localhost/api/documents/options", {
      method: "POST",
      body: JSON.stringify({ documentId: "doc_1", workspaceId: "ws_1", options: { wideLayout: true } }),
    }));

    expect(executePageWriteBridgeCommand).toHaveBeenCalled();
  });

  it("save route delegates to unified page write adapter", async () => {
    await postSave(new Request("http://localhost/api/documents/save", {
      method: "POST",
      body: JSON.stringify({ documentId: "doc_1", workspaceId: "ws_1", content: [] }),
    }));

    expect(executePageWriteBridgeCommand).toHaveBeenCalled();
  });
});
