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

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

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

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

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

describe("useChildSummary", () => {
  it("无 currentChildId 时暂停查询，返回 null 且不加载", () => {
    const { result } = renderUseChildSummary();
    expect(result.current.summary).toBeNull();
    expect(result.current.loading).toBe(false);
    expect(result.current.error).toBeUndefined();
  });

  it("有 currentChildId 时加载成功返回概览", async () => {
    useChildStore.setState({ currentChildId: "student-001" });
    const { result } = renderUseChildSummary();
    await waitFor(() => {
      expect(result.current.summary).not.toBeNull();
    });
    expect(result.current.summary?.childId).toBe("student-001");
    expect(result.current.summary?.avgScore).toBe(90);
    expect(result.current.summary?.classRank).toBe(5);
    expect(result.current.summary?.attendanceRate).toBe(0.96);
    expect(result.current.summary?.pendingHomeworkCount).toBe(3);
    expect(result.current.summary?.recentGradeTrend).toBe("up");
    expect(result.current.summary?.recentScores).toHaveLength(4);
    expect(result.current.summary?.upcomingEvents).toHaveLength(2);
    expect(result.current.loading).toBe(false);
    expect(result.current.error).toBeUndefined();
  });

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

  it("GraphQL 返回错误时透传 error", async () => {
    useChildStore.setState({ currentChildId: "student-001" });
    server.resetHandlers(
      graphql.query("ChildSummary", () =>
        HttpResponse.json({ errors: [{ message: "无权限" }] }, { status: 200 }),
      ),
    );

    const { result } = renderUseChildSummary();
    await waitFor(() => {
      expect(result.current.error).toBeDefined();
    });
    expect(result.current.summary).toBeNull();
    expect(result.current.loading).toBe(false);
    expect(result.current.error?.message).toContain("无权限");
  });

  it("切换 currentChildId 后重新请求", async () => {
    server.resetHandlers(
      graphql.query("ChildSummary", ({ variables }) => {
        const childId = variables.childId as string;
        return HttpResponse.json({
          data: {
            childSummary: {
              childId,
              avgScore: 90,
              classRank: 5,
              classSize: 45,
              attendanceRate: 0.96,
              pendingHomeworkCount: 3,
              recentGradeTrend: "up",
              recentScores: [],
            },
          },
        });
      }),
    );
    useChildStore.setState({ currentChildId: "student-001" });
    const { result } = renderUseChildSummary();
    await waitFor(
      () => {
        expect(result.current.summary?.childId).toBe("student-001");
      },
      { timeout: 4000 },
    );

    useChildStore.setState({ currentChildId: "student-002" });
    await waitFor(
      () => {
        expect(result.current.summary?.childId).toBe("student-002");
      },
      { timeout: 4000 },
    );
  });

  it("查询返回空数据时 summary 为 null", async () => {
    useChildStore.setState({ currentChildId: "student-001" });
    server.resetHandlers(
      graphql.query("ChildSummary", () =>
        HttpResponse.json({ data: { childSummary: null } }),
      ),
    );

    const { result } = renderUseChildSummary();
    await waitFor(() => {
      expect(result.current.loading).toBe(false);
    });
    expect(result.current.summary).toBeNull();
  });
});
