// useChildExamResult Hook 单测
// 依据：02-architecture-design.md §4.2 GraphQL 接入
// 覆盖：无 currentChildId 暂停 / 无 examId 暂停 / 加载态 / 成功返回 / 错误态

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

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

function renderUseChildExamResult(examId: string) {
  const client = createTestClient();
  const wrapper = ({ children }: { children: ReactNode }) => (
    <UrqlProvider value={client}>{children}</UrqlProvider>
  );
  return renderHook(() => useChildExamResult(examId), { wrapper });
}

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

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

describe("useChildExamResult", () => {
  it("无 currentChildId 时暂停查询，返回 null", () => {
    const { result } = renderUseChildExamResult("exam-001");
    expect(result.current.result).toBeNull();
    expect(result.current.loading).toBe(false);
    expect(result.current.error).toBeUndefined();
  });

  it("无 examId 时暂停查询，返回 null", () => {
    useChildStore.setState({ currentChildId: "student-001" });
    const { result } = renderUseChildExamResult("");
    expect(result.current.result).toBeNull();
    expect(result.current.loading).toBe(false);
    expect(result.current.error).toBeUndefined();
  });

  it("有 currentChildId 和 examId 时加载成功返回考试结果", async () => {
    useChildStore.setState({ currentChildId: "student-001" });
    const { result } = renderUseChildExamResult("exam-001");
    await waitFor(() => {
      expect(result.current.result).not.toBeNull();
    });
    expect(result.current.result?.examId).toBe("exam-001");
    expect(result.current.result?.examName).toBe("期中数学测验");
    expect(result.current.result?.score).toBe(78);
    expect(result.current.result?.maxScore).toBe(100);
    expect(result.current.result?.grade).toBe("B+");
    expect(result.current.result?.questionResults).toHaveLength(5);
    expect(result.current.loading).toBe(false);
    expect(result.current.error).toBeUndefined();
  });

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

  it("查询变量携带 childId 和 examId", async () => {
    useChildStore.setState({ currentChildId: "student-001" });
    let capturedVars: unknown = null;
    server.resetHandlers(
      graphql.query("ChildExamResult", ({ variables }) => {
        capturedVars = variables;
        return HttpResponse.json({
          data: {
            childExamResult: {
              examId: "exam-001",
              examName: "test",
              score: 80,
              maxScore: 100,
              grade: "B",
              submittedAt: "2026-03-15T10:45:00Z",
              durationSeconds: 3600,
              questionResults: [],
            },
          },
        });
      }),
    );

    const { result } = renderUseChildExamResult("exam-001");
    await waitFor(() => {
      expect(result.current.result).not.toBeNull();
    });
    expect(capturedVars).toEqual({
      childId: "student-001",
      examId: "exam-001",
    });
  });

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

    const { result } = renderUseChildExamResult("exam-001");
    await waitFor(() => {
      expect(result.current.error).toBeDefined();
    });
    expect(result.current.result).toBeNull();
    expect(result.current.error?.message).toContain("考试结果查询失败");
  });

  it("返回空结果时 result 为 null", async () => {
    useChildStore.setState({ currentChildId: "student-001" });
    server.resetHandlers(
      graphql.query("ChildExamResult", () =>
        HttpResponse.json({ data: { childExamResult: null } }),
      ),
    );

    const { result } = renderUseChildExamResult("exam-999");
    await waitFor(() => {
      expect(result.current.loading).toBe(false);
    });
    expect(result.current.result).toBeNull();
  });
});
