import { useQuery } from "@tanstack/react-query";
import { fetchSectorRecordReport } from "@/record-management/services/api/sectorReportService";
import { SectorReportFilters } from "./types";
import {
  fetchPositionsByRankAndUnit,
  getChildPositions,
} from "@/user-management/services/api/positionService";

export const useSectorReport = (filters: SectorReportFilters) =>
  useQuery({
    queryKey: [
      "sector-record-report",
      filters.unitId,
      filters.positionId,
      filters.from,
      filters.to,
    ],
    queryFn: () => fetchSectorRecordReport(filters),
    enabled: Boolean(filters.unitId),
    staleTime: 60 * 1000,
  });

export const usePositionsByRankAndUnit = (unitId: string, rank: number) =>
  useQuery({
    queryKey: ["positions-by-rank-and-unit", unitId, rank],
    queryFn: () => fetchPositionsByRankAndUnit(unitId, rank),
    enabled: Boolean(unitId),
    staleTime: 5 * 60 * 1000,
  });

export const useChildPositions = (parentPositionId: string) =>
  useQuery({
    queryKey: ["child-positions", parentPositionId],
    queryFn: async () => {
      const response = await getChildPositions(parentPositionId);
      const data = response.data;
      return Array.isArray(data) ? data : (data?.items ?? []);
    },
    enabled: Boolean(parentPositionId),
    staleTime: 5 * 60 * 1000,
  });
