// useMyChildren：获取家长绑定子女列表
// 依据：02-architecture-design.md §4.2 GraphQL 接入
// - ISSUE-010：iam GetChildrenByParent P0 阻塞，MSW mock 返回 student-001 + student-002
// - 加载后写入 Zustand store（setChildren），触发默认选中
// - 单次加载，不轮询（子女列表变更由 WebSocket ChildBound/ChildUnbound 事件通知 P5）

"use client";

import { useEffect } from "react";
import { useQuery } from "urql";
import { MY_CHILDREN } from "@/lib/graphql/operations";
import { useChildStore } from "@/store/child-store";
import type { ChildInfo } from "@/types";

interface MyChildrenResponse {
  myChildren: ChildInfo[];
}

export function useMyChildren() {
  const setChildren = useChildStore((s) => s.setChildren);
  const setLoading = useChildStore((s) => s.setLoading);

  const [result] = useQuery<MyChildrenResponse>({
    query: MY_CHILDREN,
  });

  useEffect(() => {
    setLoading(result.fetching);
    if (result.data?.myChildren) {
      setChildren(result.data.myChildren);
    }
  }, [result.data, result.fetching, setChildren, setLoading]);

  return {
    children: result.data?.myChildren ?? [],
    loading: result.fetching,
    error: result.error,
  };
}
