// useChildErrorBook：获取子女错题本数据（统计 + Top 错题 + 薄弱知识点）
// 依据：02-architecture-design.md §4.2 GraphQL 接入
// 同时发起三个查询，合并为统一返回值

"use client";

import { useQuery, type CombinedError } from "urql";
import {
  CHILD_ERROR_BOOK_STATS,
  CHILD_TOP_WRONG_QUESTIONS,
  CHILD_WEAK_KPS,
} from "@/lib/graphql/operations";
import type { ErrorBookStats, TopWrongQuestion, WeakKp } from "@/types";
import { useChildStore } from "@/store/child-store";

interface ChildErrorBookStatsResponse {
  childErrorBookStats: ErrorBookStats;
}

interface ChildTopWrongQuestionsResponse {
  childTopWrongQuestions: TopWrongQuestion[];
}

interface ChildWeakKpsResponse {
  childWeakKps: WeakKp[];
}

export function useChildErrorBook(): {
  stats: ErrorBookStats | null;
  topWrongQuestions: TopWrongQuestion[];
  weakKps: WeakKp[];
  loading: boolean;
  error: CombinedError | undefined;
} {
  const currentChildId = useChildStore((s) => s.currentChildId);

  const [statsResult] = useQuery<ChildErrorBookStatsResponse>({
    query: CHILD_ERROR_BOOK_STATS,
    variables: { childId: currentChildId },
    pause: !currentChildId,
  });

  const [topWrongResult] = useQuery<ChildTopWrongQuestionsResponse>({
    query: CHILD_TOP_WRONG_QUESTIONS,
    variables: { childId: currentChildId, limit: 10 },
    pause: !currentChildId,
  });

  const [weakKpsResult] = useQuery<ChildWeakKpsResponse>({
    query: CHILD_WEAK_KPS,
    variables: { childId: currentChildId, limit: 10 },
    pause: !currentChildId,
  });

  return {
    stats: statsResult.data?.childErrorBookStats ?? null,
    topWrongQuestions: topWrongResult.data?.childTopWrongQuestions ?? [],
    weakKps: weakKpsResult.data?.childWeakKps ?? [],
    loading:
      statsResult.fetching ||
      topWrongResult.fetching ||
      weakKpsResult.fetching,
    error: statsResult.error ?? topWrongResult.error ?? weakKpsResult.error,
  };
}
