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

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

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

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

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

describe("useChildExams", () => {
  it("无 currentChildId 时暂停查询，返回空数组", () => {
    const { result } = renderUseChildExams();
    expect(result.current.exams).toEqual([]);
    expect(result.current.loading).toBe(false);
    expect(result.current.error).toBeUndefined();
  });

  it("有 currentChildId 时加载成功返回考试列表", async () => {
    useChildStore.setState({ currentChildId: "student-001" });
    const { result } = renderUseChildExams();
    await waitFor(() => {
      expect(result.current.exams.length).toBeGreaterThan(0);
    });
    expect(result.current.exams).toHaveLength(5);
    expect(result.current.exams[0]!.name).toBe("期中数学测验");
    expect(result.current.exams[0]!.subject).toBe("数学");
    expect(result.current.exams[0]!.status).toBe("graded");
    expect(result.current.loading).toBe(false);
    expect(result.current.error).toBeUndefined();
  });

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

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

    const { result } = renderUseChildExams();
    await waitFor(() => {
      expect(result.current.error).toBeDefined();
    });
    expect(result.current.exams).toEqual([]);
    expect(result.current.error?.message).toContain("考试查询失败");
  });

  it("返回空考试列表", async () => {
    useChildStore.setState({ currentChildId: "student-001" });
    server.resetHandlers(
      graphql.query("ChildExams", () =>
        HttpResponse.json({ data: { childExams: [] } }),
      ),
    );

    const { result } = renderUseChildExams();
    await waitFor(() => {
      expect(result.current.loading).toBe(false);
    });
    expect(result.current.exams).toEqual([]);
  });

  it("切换 currentChildId 后重新请求", async () => {
    server.resetHandlers(
      graphql.query("ChildExams", ({ variables }) => {
        const childId = variables.childId as string;
        return HttpResponse.json({
          data: {
            childExams:
              childId === "student-001"
                ? [
                    {
                      id: "exam-001",
                      name: "数学测验",
                      subject: "数学",
                      status: "graded",
                      startsAt: "2026-03-15T09:00:00Z",
                      expiresAt: "2026-03-15T11:00:00Z",
                      durationSeconds: 7200,
                      questionCount: 25,
                      totalScore: 100,
                    },
                  ]
                : [],
          },
        });
      }),
    );
    useChildStore.setState({ currentChildId: "student-001" });
    const { result } = renderUseChildExams();
    await waitFor(
      () => {
        expect(result.current.exams.length).toBeGreaterThan(0);
      },
      { timeout: 4000 },
    );

    useChildStore.setState({ currentChildId: "student-002" });
    await waitFor(
      () => {
        expect(result.current.exams).toEqual([]);
      },
      { timeout: 4000 },
    );
  });
});
