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

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

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

function renderUseChildLessonPlanDetail(planId: string) {
  const client = createTestClient();
  const wrapper = ({ children }: { children: ReactNode }) => (
    <UrqlProvider value={client}>{children}</UrqlProvider>
  );
  return renderHook(() => useChildLessonPlanDetail(planId), { wrapper });
}

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

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

describe("useChildLessonPlanDetail", () => {
  it("无 currentChildId 时暂停查询，返回 null", () => {
    const { result } = renderUseChildLessonPlanDetail("lp-002");
    expect(result.current.lessonPlan).toBeNull();
    expect(result.current.loading).toBe(false);
    expect(result.current.error).toBeUndefined();
  });

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

  it("有 currentChildId 和 planId 时加载成功返回备课详情", async () => {
    useChildStore.setState({ currentChildId: "student-001" });
    const { result } = renderUseChildLessonPlanDetail("lp-002");
    await waitFor(() => {
      expect(result.current.lessonPlan).not.toBeNull();
    });
    expect(result.current.lessonPlan?.id).toBe("lp-002");
    expect(result.current.lessonPlan?.title).toBe("配方法解一元二次方程");
    expect(result.current.lessonPlan?.objectives).toHaveLength(3);
    expect(result.current.lessonPlan?.keyPoints).toHaveLength(2);
    expect(result.current.lessonPlan?.difficultPoints).toHaveLength(2);
    expect(result.current.lessonPlan?.content).toContain("配方法");
    expect(result.current.lessonPlan?.homeworkDescription).toContain(
      "课本第 25 页",
    );
    expect(result.current.loading).toBe(false);
    expect(result.current.error).toBeUndefined();
  });

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

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

    const { result } = renderUseChildLessonPlanDetail("lp-002");
    await waitFor(() => {
      expect(result.current.error).toBeDefined();
    });
    expect(result.current.lessonPlan).toBeNull();
    expect(result.current.error?.message).toContain("备课详情查询失败");
  });

  it("详情为 null 时返回 null", async () => {
    useChildStore.setState({ currentChildId: "student-001" });
    server.resetHandlers(
      graphql.query("ChildLessonPlanDetail", () =>
        HttpResponse.json({ data: { childLessonPlanDetail: null } }),
      ),
    );

    const { result } = renderUseChildLessonPlanDetail("not-exist");
    await waitFor(() => {
      expect(result.current.loading).toBe(false);
    });
    expect(result.current.lessonPlan).toBeNull();
  });
});
