// TanStack Query client 单测
// 依据：02-architecture-design.md §4.3 状态管理分层（Server Cache 层）
// 覆盖：默认配置（retry / staleTime / gcTime / refetchOnWindowFocus / refetchOnReconnect）

import { describe, it, expect } from "vitest";
import { createQueryClient } from "./query-client";

describe("createQueryClient", () => {
  it("返回 QueryClient 实例", () => {
    const client = createQueryClient();
    expect(client).toBeDefined();
    expect(typeof client.getQueryData).toBe("function");
    expect(typeof client.setQueryData).toBe("function");
  });

  it("每次调用返回新实例", () => {
    const a = createQueryClient();
    const b = createQueryClient();
    expect(a).not.toBe(b);
  });

  it("queries.retry 为函数（自定义策略）", () => {
    const client = createQueryClient();
    const retry = client.getDefaultOptions().queries?.retry;
    expect(typeof retry).toBe("function");
  });

  it("queries.retry 401 错误返回 false（不重试）", () => {
    const client = createQueryClient();
    const retry = client.getDefaultOptions().queries?.retry as (
      failureCount: number,
      error: unknown,
    ) => boolean;
    expect(retry(0, new Error("Request failed with status 401"))).toBe(false);
    expect(retry(1, new Error("401 Unauthorized"))).toBe(false);
  });

  it("queries.retry 网络错误在 failureCount<2 时返回 true", () => {
    const client = createQueryClient();
    const retry = client.getDefaultOptions().queries?.retry as (
      failureCount: number,
      error: unknown,
    ) => boolean;
    expect(retry(0, new Error("network error"))).toBe(true);
    expect(retry(1, new Error("network error"))).toBe(true);
  });

  it("queries.retry 失败次数 >= 2 时返回 false", () => {
    const client = createQueryClient();
    const retry = client.getDefaultOptions().queries?.retry as (
      failureCount: number,
      error: unknown,
    ) => boolean;
    expect(retry(2, new Error("network error"))).toBe(false);
    expect(retry(5, new Error("network error"))).toBe(false);
  });

  it("queries.staleTime 为 30s", () => {
    const client = createQueryClient();
    expect(client.getDefaultOptions().queries?.staleTime).toBe(30 * 1000);
  });

  it("queries.gcTime 为 5min", () => {
    const client = createQueryClient();
    expect(client.getDefaultOptions().queries?.gcTime).toBe(5 * 60 * 1000);
  });

  it("queries.refetchOnWindowFocus 为 false", () => {
    const client = createQueryClient();
    expect(client.getDefaultOptions().queries?.refetchOnWindowFocus).toBe(
      false,
    );
  });

  it("queries.refetchOnReconnect 为 always", () => {
    const client = createQueryClient();
    expect(client.getDefaultOptions().queries?.refetchOnReconnect).toBe(
      "always",
    );
  });

  it("mutations.retry 为 false", () => {
    const client = createQueryClient();
    expect(client.getDefaultOptions().mutations?.retry).toBe(false);
  });
});
