// useChildLeaveRequests：获取子女请假记录列表
// 依据：02-architecture-design.md §4.2 GraphQL 接入

"use client";

import { useQuery, type CombinedError } from "urql";
import { CHILD_LEAVE_REQUESTS } from "@/lib/graphql/operations";
import type { LeaveRequest } from "@/types";
import { useChildStore } from "@/store/child-store";

interface ChildLeaveRequestsResponse {
  childLeaveRequests: LeaveRequest[];
}

export function useChildLeaveRequests(): {
  leaveRequests: LeaveRequest[];
  loading: boolean;
  error: CombinedError | undefined;
  refetch: () => void;
} {
  const currentChildId = useChildStore((s) => s.currentChildId);

  const [result, reexecuteQuery] = useQuery<ChildLeaveRequestsResponse>({
    query: CHILD_LEAVE_REQUESTS,
    variables: { childId: currentChildId },
    pause: !currentChildId,
  });

  return {
    leaveRequests: result.data?.childLeaveRequests ?? [],
    loading: result.fetching,
    error: result.error,
    refetch: () => reexecuteQuery({ requestPolicy: "network-only" }),
  };
}
