// useChildPractice Hook 单测
// 依据：02-architecture-design.md §4.2 GraphQL 接入
// 覆盖：无 currentChildId 暂停 / 加载态 / 成功返回 / 错误态 / 两个查询合并

import {
  describe,
  it,
  expect,
  beforeAll,
  afterAll,
  afterEach,
  beforeEach,
} from "vitest";
import { renderHook, waitFor, cleanup } from "@testing-library/react";
import {
  Provider as UrqlProvider,
  Client,
  cacheExchange,
  fetchExchange,
} from "urql";
import { graphql, HttpResponse } from "msw";
import type { ReactNode } from "react";
import { server } from "@/test/mocks/server";
import { useChildStore } from "@/store/child-store";
import { useChildPractice } from "./useChildPractice";

function createTestClient(): Client {
  return new Client({
    url: "/api/v1/parent/v1/graphql",
    exchanges: [cacheExchange, fetchExchange],
    fetchOptions: { headers: { "X-Requested-With": "XMLHttpRequest" } },
  });
}

function renderUseChildPractice() {
  const client = createTestClient();
  const wrapper = ({ children }: { children: ReactNode }) => (
    <UrqlProvider value={client}>{children}</UrqlProvider>
  );
  return renderHook(() => useChildPractice(), { wrapper });
}

beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
afterEach(() => {
  cleanup();
  server.resetHandlers();
});
afterAll(() => server.close());

beforeEach(() => {
  localStorage.clear();
  useChildStore.setState({
    children: [],
    currentChildId: null,
    isLoading: false,
  });
});

describe("useChildPractice", () => {
  it("无 currentChildId 时暂停查询，返回空数据", () => {
    const { result } = renderUseChildPractice();
    expect(result.current.stats).toBeNull();
    expect(result.current.sessions).toEqual([]);
    expect(result.current.loading).toBe(false);
    expect(result.current.error).toBeUndefined();
  });

  it("有 currentChildId 时加载成功返回练习数据", async () => {
    useChildStore.setState({ currentChildId: "student-001" });
    const { result } = renderUseChildPractice();
    await waitFor(() => {
      expect(result.current.stats).not.toBeNull();
    });
    expect(result.current.stats?.totalSessions).toBe(48);
    expect(result.current.stats?.completedSessions).toBe(42);
    expect(result.current.stats?.totalQuestionsAnswered).toBe(560);
    expect(result.current.stats?.overallAccuracy).toBe(0.83);
    expect(result.current.sessions).toHaveLength(5);
    expect(result.current.sessions[0]!.subject).toBe("数学");
    expect(result.current.sessions[0]!.questionCount).toBe(20);
    expect(result.current.loading).toBe(false);
    expect(result.current.error).toBeUndefined();
  });

  it("加载中 loading 为 true", () => {
    useChildStore.setState({ currentChildId: "student-001" });
    const { result } = renderUseChildPractice();
    expect(result.current.loading).toBe(true);
  });

  it("ChildPracticeStats 返回错误时透传 error", async () => {
    useChildStore.setState({ currentChildId: "student-001" });
    server.use(
      graphql.query("ChildPracticeStats", () =>
        HttpResponse.json(
          { errors: [{ message: "练习统计查询失败" }] },
          { status: 200 },
        ),
      ),
    );

    const { result } = renderUseChildPractice();
    await waitFor(() => {
      expect(result.current.error).toBeDefined();
    });
    expect(result.current.stats).toBeNull();
    expect(result.current.error?.message).toContain("练习统计查询失败");
  });

  it("ChildPracticeSessions 返回错误时透传 error", async () => {
    useChildStore.setState({ currentChildId: "student-001" });
    server.use(
      graphql.query("ChildPracticeSessions", () =>
        HttpResponse.json(
          { errors: [{ message: "练习历史查询失败" }] },
          { status: 200 },
        ),
      ),
    );

    const { result } = renderUseChildPractice();
    await waitFor(() => {
      expect(result.current.error).toBeDefined();
    });
    expect(result.current.sessions).toEqual([]);
    expect(result.current.error?.message).toContain("练习历史查询失败");
  });

  it("两个查询返回空数据时返回空数组与 null stats", async () => {
    useChildStore.setState({ currentChildId: "student-001" });
    server.use(
      graphql.query("ChildPracticeStats", () =>
        HttpResponse.json({ data: { childPracticeStats: null } }),
      ),
      graphql.query("ChildPracticeSessions", () =>
        HttpResponse.json({ data: { childPracticeSessions: [] } }),
      ),
    );

    const { result } = renderUseChildPractice();
    await waitFor(() => {
      expect(result.current.loading).toBe(false);
    });
    expect(result.current.stats).toBeNull();
    expect(result.current.sessions).toEqual([]);
  });
});
