// useChildAttendance：获取子女考勤记录
// 依据：02-architecture-design.md §4.2 GraphQL 接入

"use client";

import { useMemo } from "react";
import { useQuery } from "urql";
import { CHILD_ATTENDANCE } from "@/lib/graphql/operations";
import type { AttendanceRecord } from "@/types";
import { useChildStore } from "@/store/child-store";

interface ChildAttendanceResponse {
  childAttendance: AttendanceRecord[];
}

function getCurrentMonthRange(): { startDate: string; endDate: string } {
  const now = new Date();
  const start = new Date(now.getFullYear(), now.getMonth(), 1);
  const end = new Date(now.getFullYear(), now.getMonth() + 1, 0);
  return {
    startDate: start.toISOString().slice(0, 10),
    endDate: end.toISOString().slice(0, 10),
  };
}

export function useChildAttendance() {
  const currentChildId = useChildStore((s) => s.currentChildId);
  const { startDate, endDate } = useMemo(getCurrentMonthRange, []);

  const [result] = useQuery<ChildAttendanceResponse>({
    query: CHILD_ATTENDANCE,
    variables: { childId: currentChildId, startDate, endDate },
    pause: !currentChildId,
  });

  return {
    attendance: result.data?.childAttendance ?? [],
    loading: result.fetching,
    error: result.error,
  };
}
