import { useQuery } from 'react-query';

import { orgChartKeys } from 'src/pages/dashboard/orgChart/queries';
import { getUserSubordinates } from 'src/services/orgChart';

import { goalsKeys } from '../../queries';
import { getGoal } from '../../services';

type UseNewGoalQueriesParams = {
  goalId: number | null;
  loggedUserId: number | undefined;
};

export function useNewGoalQueries({
  goalId,
  loggedUserId,
}: UseNewGoalQueriesParams) {
  const { data: goal, isLoading: isGoalLoading } = useQuery(
    goalsKeys.detail(goalId),
    () => {
      if (goalId == null) {
        throw new Error('goalId is required when goal detail query runs');
      }
      return getGoal(goalId);
    },
    {
      select: response => response.data,
      enabled: !!goalId,
    },
  );

  const { data: subordinates } = useQuery(
    orgChartKeys.detailSubordinates(loggedUserId ?? -1),
    () => {
      if (loggedUserId == null) {
        throw new Error(
          'loggedUserId is required when subordinates query runs',
        );
      }
      return getUserSubordinates(loggedUserId);
    },
    {
      select: response => response.data,
      enabled: !!loggedUserId,
    },
  );

  return { goal, isGoalLoading, subordinates };
}
