import { useQuery } from 'react-query';

import { getSessionAttendanceStats } from 'src/pages/dashboard/Learning/Sessions/services';
import { type RequestError, type RequestSuccess } from 'src/types/services';
import { sToMs } from 'src/utils/timeUtils';

import { sessionsKeys } from '../queries';

export type TSuccess = RequestSuccess<typeof getSessionAttendanceStats>;
export type TError = RequestError;
export type TData = TSuccess['data'];

export const useGetSessionAttendanceStats = (sessionId?: number) => {
  return useQuery<TSuccess, TError, TData>({
    queryKey: sessionsKeys.attendance.stats(sessionId!),
    queryFn: () => {
      if (!sessionId) throw new Error('Session ID is required');
      return getSessionAttendanceStats(sessionId);
    },
    select: response => response.data,
    enabled: !!sessionId,
    staleTime: sToMs(60),
  });
};
