import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { HttpError } from "../../../shared/api/errors";
import { toCategoryLoadError } from "../categoryState";

describe("F3 async state boundaries", () => {
  it("分类契约错误保留message、HTTP状态和requestId", () => {
    expect(toCategoryLoadError(new HttpError({
      httpStatus: 500,
      code: "INTERNAL_ERROR",
      message: "后端响应错误",
      details: null,
      requestId: "request-id",
    }))).toEqual({
      message: "后端响应错误",
      requestId: "request-id",
      code: "INTERNAL_ERROR",
      httpStatus: 500,
    });
  });

  it("分类搜索具有300ms防抖、AbortController和过期请求保护", () => {
    const source = readFileSync(
      new URL("../categoryState.ts", import.meta.url),
      "utf8",
    );
    expect(source).toContain("debounceMs = 300");
    expect(source).toContain("new AbortController()");
    expect(source).toContain("currentRequest !== requestVersion.current");
    expect(source).toContain("controller.abort()");
  });

  it("组织和人员查询支持取消、分页上限及卸载保护", () => {
    const source = readFileSync(
      new URL("../../directory/directoryState.ts", import.meta.url),
      "utf8",
    );
    expect(source).toContain("debounceMs = 300");
    expect(source).toContain("Math.min(pageSize ?? 20, 100)");
    expect(source).toContain("current !== version.current");
    expect(source).toContain("controller.abort()");
  });
});

