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

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

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

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

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

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

  it("有 currentChildId 时加载成功返回考勤记录", async () => {
    useChildStore.setState({ currentChildId: "student-001" });
    const { result } = renderUseChildAttendance();
    await waitFor(() => {
      expect(result.current.attendance.length).toBeGreaterThan(0);
    });
    expect(result.current.loading).toBe(false);
    expect(result.current.error).toBeUndefined();
    // 验证记录结构
    const first = result.current.attendance[0]!;
    expect(first).toHaveProperty("id");
    expect(first).toHaveProperty("date");
    expect(first).toHaveProperty("status");
  });

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

  it("查询变量包含当前月份的 startDate 和 endDate", async () => {
    useChildStore.setState({ currentChildId: "student-001" });
    let capturedVars: unknown = null;
    server.resetHandlers(
      graphql.query("ChildAttendance", ({ variables }) => {
        capturedVars = variables;
        return HttpResponse.json({ data: { childAttendance: [] } });
      }),
    );

    const { result } = renderUseChildAttendance();
    await waitFor(() => {
      expect(result.current.loading).toBe(false);
    });
    const vars = capturedVars as {
      childId: string;
      startDate: string;
      endDate: string;
    };
    expect(vars.childId).toBe("student-001");
    expect(vars.startDate).toMatch(/^\d{4}-\d{2}-\d{2}$/);
    expect(vars.endDate).toMatch(/^\d{4}-\d{2}-\d{2}$/);
    // startDate 应为本月 1 号
    const now = new Date();
    const expectedStart = new Date(now.getFullYear(), now.getMonth(), 1)
      .toISOString()
      .slice(0, 10);
    expect(vars.startDate).toBe(expectedStart);
  });

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

    const { result } = renderUseChildAttendance();
    await waitFor(() => {
      expect(result.current.error).toBeDefined();
    });
    expect(result.current.attendance).toEqual([]);
    expect(result.current.error?.message).toContain("考勤查询失败");
  });

  it("切换 currentChildId 后重新请求", async () => {
    server.resetHandlers(
      graphql.query("ChildAttendance", ({ variables }) => {
        const childId = variables.childId as string;
        return HttpResponse.json({
          data: {
            childAttendance:
              childId === "student-001"
                ? [
                    {
                      id: "att-1",
                      date: "2026-07-01",
                      status: "present",
                    },
                  ]
                : [],
          },
        });
      }),
    );
    useChildStore.setState({ currentChildId: "student-001" });
    const { result } = renderUseChildAttendance();
    await waitFor(
      () => {
        expect(result.current.attendance.length).toBeGreaterThan(0);
      },
      { timeout: 4000 },
    );

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