// useChildGrowthArchive Hook 单测
// 依据：02-architecture-design.md §4.2 GraphQL 接入
// 覆盖：无 currentChildId 暂停 / 加载态 / 成功返回 / subject 过滤 / 错误态 / 可选 childId

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

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

function renderUseChildGrowthArchive(options?: {
  childId?: string;
  subject?: string;
}) {
  const client = createTestClient();
  const wrapper = ({ children }: { children: ReactNode }) => (
    <UrqlProvider value={client}>{children}</UrqlProvider>
  );
  return renderHook(() => useChildGrowthArchive(options), { wrapper });
}

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

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

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

  it("有 currentChildId 时加载成功返回成长档案", async () => {
    useChildStore.setState({ currentChildId: "student-001" });
    const { result } = renderUseChildGrowthArchive();
    await waitFor(() => {
      expect(result.current.growthArchive).not.toBeNull();
    });
    expect(result.current.growthArchive?.childId).toBe("student-001");
    expect(result.current.growthArchive?.subject).toBe("数学");
    expect(result.current.growthArchive?.dataPoints).toHaveLength(4);
    expect(result.current.growthArchive?.dataPoints[0]?.studentScore).toBe(82);
    expect(result.current.growthArchive?.dataPoints[0]?.classAverage).toBe(76);
    expect(result.current.loading).toBe(false);
    expect(result.current.error).toBeUndefined();
  });

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

  it("传入 subject 时变量携带 subject", async () => {
    useChildStore.setState({ currentChildId: "student-001" });
    let capturedVars: unknown = null;
    server.resetHandlers(
      graphql.query("ChildGrowthArchive", ({ variables }) => {
        capturedVars = variables;
        return HttpResponse.json({
          data: {
            childGrowthArchive: {
              childId: "student-001",
              subject: "数学",
              dataPoints: [],
            },
          },
        });
      }),
    );

    const { result } = renderUseChildGrowthArchive({ subject: "数学" });
    await waitFor(() => {
      expect(result.current.loading).toBe(false);
    });
    expect(capturedVars).toEqual({
      childId: "student-001",
      subject: "数学",
    });
  });

  it("未传 subject 时变量 subject 为 null", async () => {
    useChildStore.setState({ currentChildId: "student-001" });
    let capturedVars: unknown = null;
    server.resetHandlers(
      graphql.query("ChildGrowthArchive", ({ variables }) => {
        capturedVars = variables;
        return HttpResponse.json({
          data: {
            childGrowthArchive: {
              childId: "student-001",
              subject: "数学",
              dataPoints: [],
            },
          },
        });
      }),
    );

    const { result } = renderUseChildGrowthArchive();
    await waitFor(() => {
      expect(result.current.loading).toBe(false);
    });
    expect(capturedVars).toEqual({
      childId: "student-001",
      subject: null,
    });
  });

  it("传入 childId 覆盖 store 中的 currentChildId", async () => {
    useChildStore.setState({ currentChildId: "student-001" });
    let capturedVars: unknown = null;
    server.resetHandlers(
      graphql.query("ChildGrowthArchive", ({ variables }) => {
        capturedVars = variables;
        return HttpResponse.json({
          data: {
            childGrowthArchive: {
              childId: variables.childId as string,
              subject: "数学",
              dataPoints: [],
            },
          },
        });
      }),
    );

    const { result } = renderUseChildGrowthArchive({ childId: "student-002" });
    await waitFor(() => {
      expect(result.current.growthArchive?.childId).toBe("student-002");
    });
    const vars = capturedVars as { childId: string };
    expect(vars.childId).toBe("student-002");
  });

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

    const { result } = renderUseChildGrowthArchive();
    await waitFor(() => {
      expect(result.current.error).toBeDefined();
    });
    expect(result.current.growthArchive).toBeNull();
    expect(result.current.error?.message).toContain("成长档案查询失败");
  });

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

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