import { beforeEach, describe, expect, it, vi } from "vitest";
import {
  clearDetailCacheForTests,
  loadDetailOnce,
} from "../documentState";
import { detail } from "./fixtures";

describe("detail request deduplication", () => {
  beforeEach(clearDetailCacheForTests);

  it("重复渲染或并发打开只发起一次必要的详情请求", async () => {
    const loader = vi.fn().mockResolvedValue(detail);
    const [first, second] = await Promise.all([
      loadDetailOnce("document", "1", loader),
      loadDetailOnce("document", "1", loader),
    ]);
    expect(first).toEqual(detail);
    expect(second).toEqual(detail);
    expect(loader).toHaveBeenCalledTimes(1);
  });

  it("文档详情与附件详情使用独立缓存键", async () => {
    const loader = vi.fn().mockResolvedValue(detail);
    await loadDetailOnce("document", "1", loader);
    await loadDetailOnce("attachment", "1", loader);
    expect(loader).toHaveBeenCalledTimes(2);
  });

  it("失败请求不缓存，允许用户再次打开重试", async () => {
    const loader = vi.fn().mockRejectedValueOnce(new Error("network")).mockResolvedValue(detail);
    await expect(loadDetailOnce("document", "1", loader)).rejects.toThrow("network");
    await expect(loadDetailOnce("document", "1", loader)).resolves.toEqual(detail);
    expect(loader).toHaveBeenCalledTimes(2);
  });
});
