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

import {
  describe,
  it,
  expect,
  beforeAll,
  afterAll,
  afterEach,
} 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 { useAcademicYears } from "./useAcademicYears";

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

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

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

describe("useAcademicYears", () => {
  it("加载中 loading 为 true", () => {
    const { result } = renderUseAcademicYears();
    expect(result.current.loading).toBe(true);
    expect(result.current.academicYears).toEqual([]);
  });

  it("加载成功返回学年列表", async () => {
    const { result } = renderUseAcademicYears();
    await waitFor(() => {
      expect(result.current.academicYears.length).toBeGreaterThan(0);
    });
    expect(result.current.academicYears).toHaveLength(2);
    expect(result.current.academicYears[0]!.id).toBe("ay-2025-2026");
    expect(result.current.academicYears[0]!.name).toBe("2025-2026");
    expect(result.current.loading).toBe(false);
    expect(result.current.error).toBeUndefined();
  });

  it("GraphQL 返回错误时透传 error", async () => {
    server.resetHandlers(
      graphql.query("AcademicYears", () =>
        HttpResponse.json(
          { errors: [{ message: "学年查询失败" }] },
          { status: 200 },
        ),
      ),
    );

    const { result } = renderUseAcademicYears();
    await waitFor(() => {
      expect(result.current.error).toBeDefined();
    });
    expect(result.current.academicYears).toEqual([]);
    expect(result.current.error?.message).toContain("学年查询失败");
  });
});
