import { useMemo } from 'react';
import { useQuery } from 'react-query';

import useFormatDate from 'src/hooks/useFormatDate';
import { simpleDateStringToLocalDate } from 'src/utils/date';

import { SESSIONS_STALE_TIME } from '../constants';
import { sessionsKeys } from '../queries';
import { getSession } from '../services';

export const useGetSession = (sessionId?: number) => {
  const { formatDate } = useFormatDate();

  const { data, ...query } = useQuery({
    queryKey: sessionsKeys.detail(sessionId),
    queryFn: () => {
      if (!sessionId) throw new Error('Session ID is required');
      return getSession(sessionId);
    },
    select: response => response.data,
    enabled: !!sessionId,
    staleTime: SESSIONS_STALE_TIME,
  });

  const formattedSession = useMemo(() => {
    if (!data) return undefined;

    return {
      ...data,
      localDate: formatDate(simpleDateStringToLocalDate(data.localDate)),
    };
  }, [data, formatDate]);

  return {
    session: formattedSession,
    ...query,
  };
};
