// useChildDetail Hook 单测
// 依据：02-architecture-design.md §4.2 GraphQL 接入
// 覆盖：无 childId 暂停 / 加载态 / 成功返回 / 变量传递 / 错误态

import {
  describe,
  it,
  expect,
  beforeAll,
  afterAll,
  afterEach,
} 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 { useChildDetail } from "./useChildDetail";

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

function renderUseChildDetail(childId: string) {
  const client = createTestClient();
  const wrapper = ({ children }: { children: ReactNode }) => (
    <UrqlProvider value={client}>{children}</UrqlProvider>
  );
  return renderHook(() => useChildDetail(childId), { wrapper });
}

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

describe("useChildDetail", () => {
  it("无 childId 时暂停查询，返回 null", () => {
    const { result } = renderUseChildDetail("");
    expect(result.current.childDetail).toBeNull();
    expect(result.current.loading).toBe(false);
    expect(result.current.error).toBeUndefined();
  });

  it("有 childId 时加载成功返回子女详情", async () => {
    const { result } = renderUseChildDetail("student-001");
    await waitFor(() => {
      expect(result.current.childDetail).not.toBeNull();
    });
    expect(result.current.childDetail?.childId).toBe("student-001");
    expect(result.current.childDetail?.basicInfo.name).toBe("张小明");
    expect(result.current.childDetail?.basicInfo.className).toBe("初一(1)班");
    expect(result.current.childDetail?.todaySchedule.length).toBeGreaterThan(0);
    expect(result.current.childDetail?.weeklySchedule.length).toBeGreaterThan(0);
    expect(result.current.childDetail?.homeworkSummary).toBeDefined();
    expect(result.current.childDetail?.gradeSummary).toBeDefined();
    expect(result.current.childDetail?.examResults).toBeDefined();
    expect(result.current.loading).toBe(false);
    expect(result.current.error).toBeUndefined();
  });

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

  it("传入的 childId 变量正确传递", async () => {
    let capturedVars: unknown = null;
    server.resetHandlers(
      graphql.query("ChildDetail", ({ variables }) => {
        capturedVars = variables;
        return HttpResponse.json({
          data: {
            childDetail: {
              childId: variables.childId,
              basicInfo: {
                name: "张小红",
                grade: "grade.5",
                className: "五年级(2)班",
                schoolName: "实验小学",
                relation: "父亲",
              },
              todaySchedule: [],
              weeklySchedule: [],
              homeworkSummary: {
                pendingCount: 0,
                overdueCount: 0,
                submittedCount: 0,
                gradedCount: 0,
              },
              gradeSummary: {
                avgScore: 0,
                classRank: 0,
                classSize: 0,
                trend: "stable",
              },
              examResults: {
                upcoming: 0,
                completed: 0,
                avgScore: 0,
              },
            },
          },
        });
      }),
    );

    const { result } = renderUseChildDetail("student-002");
    await waitFor(() => {
      expect(result.current.childDetail).not.toBeNull();
    });
    expect(capturedVars).toEqual({ childId: "student-002" });
    expect(result.current.childDetail?.basicInfo.name).toBe("张小红");
  });

  it("GraphQL 返回错误时透传 error", async () => {
    server.resetHandlers(
      graphql.query("ChildDetail", () =>
        HttpResponse.json(
          { errors: [{ message: "子女详情查询失败" }] },
          { status: 200 },
        ),
      ),
    );

    const { result } = renderUseChildDetail("student-001");
    await waitFor(() => {
      expect(result.current.error).toBeDefined();
    });
    expect(result.current.childDetail).toBeNull();
    expect(result.current.error?.message).toContain("子女详情查询失败");
  });
});
