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

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

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

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

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

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

  it("有 currentChildId 时加载成功返回学习路径节点", async () => {
    useChildStore.setState({ currentChildId: "student-001" });
    const { result } = renderUseChildLearningPath();
    await waitFor(() => {
      expect(result.current.nodes.length).toBeGreaterThan(0);
    });
    expect(result.current.nodes).toHaveLength(5);
    expect(result.current.nodes[0]!.name).toBe("一元一次方程");
    expect(result.current.nodes[0]!.status).toBe("completed");
    expect(result.current.nodes[0]!.mastery).toBe(0.92);
    expect(result.current.nodes[2]!.status).toBe("in-progress");
    expect(result.current.nodes[4]!.status).toBe("locked");
    expect(result.current.loading).toBe(false);
    expect(result.current.error).toBeUndefined();
  });

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

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

    const { result } = renderUseChildLearningPath();
    await waitFor(() => {
      expect(result.current.error).toBeDefined();
    });
    expect(result.current.nodes).toEqual([]);
    expect(result.current.error?.message).toContain("学习路径查询失败");
  });

  it("返回空学习路径", async () => {
    useChildStore.setState({ currentChildId: "student-001" });
    server.resetHandlers(
      graphql.query("ChildLearningPath", () =>
        HttpResponse.json({ data: { childLearningPath: [] } }),
      ),
    );

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

  it("切换 currentChildId 后重新请求", async () => {
    server.resetHandlers(
      graphql.query("ChildLearningPath", ({ variables }) => {
        const childId = variables.childId as string;
        return HttpResponse.json({
          data: {
            childLearningPath:
              childId === "student-001"
                ? [
                    {
                      id: "kp-001",
                      name: "一元一次方程",
                      knowledgePointId: "kp-001",
                      status: "completed",
                      mastery: 0.92,
                      dependencies: [],
                      recommendedOrder: 1,
                    },
                  ]
                : [],
          },
        });
      }),
    );
    useChildStore.setState({ currentChildId: "student-001" });
    const { result } = renderUseChildLearningPath();
    await waitFor(
      () => {
        expect(result.current.nodes.length).toBeGreaterThan(0);
      },
      { timeout: 4000 },
    );

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