// useChildDiagnostic 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 { useChildDiagnostic } from "./useChildDiagnostic";

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

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

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

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

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

  it("有 currentChildId 时加载成功返回诊断数据", async () => {
    useChildStore.setState({ currentChildId: "student-001" });
    const { result } = renderUseChildDiagnostic();
    await waitFor(() => {
      expect(result.current.masterySummary).not.toBeNull();
    });
    expect(result.current.masterySummary?.overallMastery).toBe(0.78);
    expect(result.current.masterySummary?.totalKps).toBe(86);
    expect(result.current.masterySummary?.masteredKps).toBe(67);
    expect(result.current.masterySummary?.subjectMastery).toHaveLength(4);
    expect(result.current.reports).toHaveLength(2);
    expect(result.current.reports[0]!.title).toBe(
      "2026 春季学期学情诊断报告",
    );
    expect(result.current.reports[0]!.status).toBe("published");
    expect(result.current.loading).toBe(false);
    expect(result.current.error).toBeUndefined();
  });

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

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

    const { result } = renderUseChildDiagnostic();
    await waitFor(() => {
      expect(result.current.error).toBeDefined();
    });
    expect(result.current.masterySummary).toBeNull();
    expect(result.current.error?.message).toContain("掌握度查询失败");
  });

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

    const { result } = renderUseChildDiagnostic();
    await waitFor(() => {
      expect(result.current.error).toBeDefined();
    });
    expect(result.current.reports).toEqual([]);
    expect(result.current.error?.message).toContain("诊断报告查询失败");
  });

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

    const { result } = renderUseChildDiagnostic();
    await waitFor(() => {
      expect(result.current.loading).toBe(false);
    });
    expect(result.current.masterySummary).toBeNull();
    expect(result.current.reports).toEqual([]);
  });
});
