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

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

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

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

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

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

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

  it("有 currentChildId 时加载成功返回请假列表", async () => {
    useChildStore.setState({ currentChildId: "student-001" });
    const { result } = renderUseChildLeaveRequests();
    await waitFor(() => {
      expect(result.current.leaveRequests.length).toBeGreaterThan(0);
    });
    // mock 中 student-001 有 2 条请假记录
    expect(result.current.leaveRequests).toHaveLength(2);
    expect(result.current.leaveRequests[0]!.type).toBe("sick");
    expect(result.current.leaveRequests[0]!.status).toBe("approved");
    expect(result.current.loading).toBe(false);
    expect(result.current.error).toBeUndefined();
  });

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

  it("refetch 触发重新查询", async () => {
    useChildStore.setState({ currentChildId: "student-001" });
    let queryCount = 0;
    server.resetHandlers(
      graphql.query("ChildLeaveRequests", () => {
        queryCount += 1;
        return HttpResponse.json({
          data: {
            childLeaveRequests: [
              {
                id: `leave-${queryCount}`,
                childId: "student-001",
                type: "sick",
                startDate: "2026-05-10",
                endDate: "2026-05-11",
                reason: "感冒发烧需要休息",
                status: "pending",
                submittedAt: "2026-05-09T20:00:00Z",
              },
            ],
          },
        });
      }),
    );

    const { result } = renderUseChildLeaveRequests();
    await waitFor(() => {
      expect(result.current.leaveRequests).toHaveLength(1);
    });
    expect(queryCount).toBe(1);

    result.current.refetch();
    await waitFor(() => {
      expect(queryCount).toBeGreaterThanOrEqual(2);
    });
  });

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

    const { result } = renderUseChildLeaveRequests();
    await waitFor(() => {
      expect(result.current.error).toBeDefined();
    });
    expect(result.current.leaveRequests).toEqual([]);
    expect(result.current.error?.message).toContain("请假查询失败");
  });
});
