import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";

const app = readFileSync(new URL("../../../app/App.tsx", import.meta.url), "utf8");
const documentState = readFileSync(new URL("../documentState.ts", import.meta.url), "utf8");
const attachmentState = readFileSync(new URL("../../attachments/attachmentState.ts", import.meta.url), "utf8");
const documentApi = readFileSync(new URL("../documentApi.ts", import.meta.url), "utf8");
const attachmentApi = readFileSync(new URL("../../attachments/attachmentApi.ts", import.meta.url), "utf8");

describe("Q2-F检索范围与并发保护", () => {
  it("三个真实区域均使用服务端查询和统一时间工具栏", () => {
    expect(app).toContain('ariaLabel="方案检索"');
    expect(app).toContain('ariaLabel="子方案检索"');
    expect(app).toContain('ariaLabel="已挂载附件检索"');
    expect(app).toContain("toUpdatedTimeRange");
    expect(app).toContain("...mainRange.query");
    expect(app).toContain("...subRange.query");
    expect(app).toContain("...mountedRange.query");
  });

  it("关键词约300ms防抖，旧请求会取消且旧响应不能覆盖新响应", () => {
    for (const source of [documentState, attachmentState]) {
      expect(source).toContain("debounceMs = 300");
      expect(source).toContain("new AbortController()");
      expect(source).toContain("controller.abort()");
      expect(source).toMatch(/requestVersion|version\.current/);
    }
  });

  it("非法区间禁用请求，筛选变化与主案切换重置页码和下方筛选", () => {
    expect(app).toContain("!mainRange.error");
    expect(app).toContain("!subRange.error");
    expect(app).toContain("!mountedRange.error");
    expect(app).toContain("setSubPage(1)");
    expect(app).toContain("setMountedPage(1)");
    expect(app).toContain("}, [selectedMainId]);");
    expect(app).toContain("}, [selected?.id]);");
  });

  it("只调用正式路径，不增加search或废止接口", () => {
    expect(documentApi).toContain('"documents"');
    expect(documentApi).toContain("`main-plans/${mainPlanId}/sub-plans`");
    expect(attachmentApi).toContain("`main-plans/${mainPlanId}/attachments`");
    for (const source of [documentApi, attachmentApi]) {
      expect(source).not.toContain("/search");
      expect(source).not.toContain("/children");
      expect(source).not.toContain("/materials");
    }
  });
});
