// useChildPractice：获取子女练习统计数据（统计 + 历史会话）
// 依据：02-architecture-design.md §4.2 GraphQL 接入
// 同时发起两个查询，合并为统一返回值

"use client";

import { useQuery, type CombinedError } from "urql";
import {
  CHILD_PRACTICE_STATS,
  CHILD_PRACTICE_SESSIONS,
} from "@/lib/graphql/operations";
import type { PracticeStats, PracticeSession } from "@/types";
import { useChildStore } from "@/store/child-store";

interface ChildPracticeStatsResponse {
  childPracticeStats: PracticeStats;
}

interface ChildPracticeSessionsResponse {
  childPracticeSessions: PracticeSession[];
}

export function useChildPractice(): {
  stats: PracticeStats | null;
  sessions: PracticeSession[];
  loading: boolean;
  error: CombinedError | undefined;
} {
  const currentChildId = useChildStore((s) => s.currentChildId);

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

  const [sessionsResult] = useQuery<ChildPracticeSessionsResponse>({
    query: CHILD_PRACTICE_SESSIONS,
    variables: { childId: currentChildId, limit: 20 },
    pause: !currentChildId,
  });

  return {
    stats: statsResult.data?.childPracticeStats ?? null,
    sessions: sessionsResult.data?.childPracticeSessions ?? [],
    loading: statsResult.fetching || sessionsResult.fetching,
    error: statsResult.error ?? sessionsResult.error,
  };
}
