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

const appSource = readFileSync(
  new URL("../../../app/App.tsx", import.meta.url),
  "utf8",
);
const auditApiSource = readFileSync(
  new URL("../auditApi.ts", import.meta.url),
  "utf8",
);
const auditStateSource = readFileSync(
  new URL("../auditState.ts", import.meta.url),
  "utf8",
);
const statisticsStateSource = readFileSync(
  new URL("../../statistics/statisticsState.ts", import.meta.url),
  "utf8",
);

describe("F7 App and request scope", () => {
  it("真实审计页仅挂载在allowedModules控制的audit路由", () => {
    expect(appSource).toContain(
      'page === "audit" &&',
    );
    expect(appSource).toContain("<AuditDashboard />");
    expect(appSource).toContain("getNavigationItems(");
    expect(appSource).toContain("currentUser.allowedModules,");
    expect(appSource).toContain('dictionaries.label("allowedModules", module)');
    expect(appSource).toContain(
      'page === "audit" && currentUser.roleCode === RoleCode.ADMIN',
    );
  });

  it("ADMIN后台挂载真实统计，审计页面不重复挂载文档统计", () => {
    const adminStart = appSource.indexOf("function RealAdminPage");
    const rootStart = appSource.indexOf("export default function App");
    const adminSource = appSource.slice(adminStart, rootStart);
    expect(adminSource).toContain("<DocumentStatisticsCards />");
    expect(appSource).toContain(
      'page === "admin" && currentUser.roleCode === RoleCode.ADMIN',
    );
    expect(auditApiSource).not.toContain("statistics/documents");
  });

  it("统计订阅F5文档和附件写操作的失效事件", () => {
    expect(statisticsStateSource).toContain(
      'useContentRevision("documents")',
    );
    expect(statisticsStateSource).toContain(
      'useContentRevision("attachments")',
    );
  });

  it("防抖、AbortController和请求版本保护均存在", () => {
    expect(auditStateSource).toContain("debounceMs = 300");
    expect(auditStateSource).toContain("new AbortController()");
    expect(auditStateSource).toContain("requestVersion");
    expect(auditStateSource).toContain("window.clearTimeout(timer)");
  });

  it("F7模块不调用导出、恢复、文件流、挂载、权限或B8接口", () => {
    for (const forbidden of [
      "audit/export",
      "/restore",
      "preview",
      "download",
      "/bind",
      "permissions",
      "statistics/storage",
    ]) {
      expect(auditApiSource).not.toContain(forbidden);
    }
  });
});
