// useChildAttendance：获取子女考勤记录
// 依据：02-architecture-design.md §4.2 GraphQL 接入
// - 支持可选 month 参数（YYYY-MM 格式），默认当前月
// - 支持可选 childId 参数，默认使用 store 中的 currentChildId

"use client";

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

interface ChildAttendanceResponse {
  childAttendance: AttendanceRecord[];
}

interface UseChildAttendanceOptions {
  childId?: string;
  month?: string; // YYYY-MM 格式
}

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),
  };
}

function getMonthRange(month: string): { startDate: string; endDate: string } {
  const [yearStr, monthStr] = month.split("-");
  const year = parseInt(yearStr ?? "0", 10);
  const monthIdx = parseInt(monthStr ?? "1", 10) - 1;
  const start = new Date(year, monthIdx, 1);
  const end = new Date(year, monthIdx + 1, 0);
  return {
    startDate: start.toISOString().slice(0, 10),
    endDate: end.toISOString().slice(0, 10),
  };
}

export function useChildAttendance(
  options?: UseChildAttendanceOptions,
): {
  attendance: AttendanceRecord[];
  loading: boolean;
  error: CombinedError | undefined;
} {
  const currentChildId = useChildStore((s) => s.currentChildId);
  const targetChildId = options?.childId ?? currentChildId;
  const { startDate, endDate } = useMemo(
    () =>
      options?.month ? getMonthRange(options.month) : getCurrentMonthRange(),
    [options?.month],
  );

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

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