import { useMutation, useQuery, useQueryClient } from 'react-query';
import { APIErrorType } from '../../api';
import {
  createIntroducer,
  CreateIntroducerDataType,
  fetchIntroducer,
  IntroducerType,
  updateIntroducer,
  UpdateIntroducerDataType
} from '../../api/introducer';
import { UseQueryResult } from 'react-query/types/react/types';

export type useUserReturnType = UseQueryResult<IntroducerType>;

export function useIntroducer(enabled: boolean = true): useUserReturnType {
  return useQuery<IntroducerType, APIErrorType>('introducer', fetchIntroducer, {
    enabled,
    staleTime: 5 * 60 * 1000,
    retry: false
  });
}

export function useCreateIntroducerMutation() {
  const queryClient = useQueryClient();

  return useMutation<IntroducerType, APIErrorType, CreateIntroducerDataType>(createIntroducer, {
    onSuccess: introducer => {
      queryClient.setQueryData('introducer', introducer);
    }
  });
}

export function useUpdateIntroducerMutation() {
  const queryClient = useQueryClient();

  return useMutation<IntroducerType, APIErrorType, UpdateIntroducerDataType>(updateIntroducer, {
    onSuccess: introducer => {
      queryClient.setQueryData('introducer', introducer);
    }
  });
}
