import { describe, expect, it, vi } from "vitest";
import type { JsonResult } from "../../../shared/api/types";
import { createOrganizationApi } from "../organizationApi";
import { createUserApi } from "../userApi";

function result<T>(data: T): JsonResult<T> {
  return {
    data,
    message: "success",
    requestId: "request-id",
    httpStatus: 200,
    headers: new Headers(),
  };
}

const organization = {
  id: "1", orgCode: "ORG_ROOT", orgName: "机关", parentId: null,
  orgPath: "/机关", sortNo: 10, status: "ENABLED", children: [],
};
const user = {
  id: "3", username: "user", realName: "普通用户", organizationId: "2",
  organizationName: "作战部", roleCode: "USER", securityLevel: "SECRET",
  status: "ENABLED", allowedModules: ["DOCUMENT_BROWSER"],
};

describe("directory APIs", () => {
  it("organizationApi使用organizations/tree和keyword", async () => {
    const get = vi.fn().mockResolvedValue(result([organization]));
    const api = createOrganizationApi({ get });
    const signal = new AbortController().signal;
    await api.getTree({ keyword: "作战", status: "ENABLED" }, signal);
    expect(get).toHaveBeenCalledWith("organizations/tree", {
      query: { keyword: "作战", status: "ENABLED" },
      signal,
    });
  });

  it("userApi传递组织、下级、关键词、状态和分页参数", async () => {
    const page = { items: [user], page: 2, pageSize: 50, total: 51, totalPages: 2 };
    const get = vi.fn().mockResolvedValue(result(page));
    const api = createUserApi({ get });
    const signal = new AbortController().signal;
    await expect(api.getUsers({
      organizationId: "2",
      includeDescendants: true,
      keyword: "user",
      status: "ENABLED",
      page: 2,
      pageSize: 50,
    }, signal)).resolves.toEqual(page);
    expect(get).toHaveBeenCalledWith("users", {
      query: {
        organizationId: "2",
        includeDescendants: true,
        keyword: "user",
        status: "ENABLED",
        page: 2,
        pageSize: 50,
      },
      signal,
    });
  });

  it("拒绝人员分页中的number ID", async () => {
    const get = vi.fn().mockResolvedValue(result({
      items: [{ ...user, id: 3 }],
      page: 1,
      pageSize: 20,
      total: 1,
      totalPages: 1,
    }));
    await expect(createUserApi({ get }).getUsers()).rejects.toMatchObject({
      message: "人员列表响应不符合DMS接口契约",
      requestId: "request-id",
    });
  });
});

