import { useMutation, useQuery, useQueryClient } from 'react-query';
import { APIErrorType } from '../../api';
import { UseQueryResult } from 'react-query/types/react/types';
import {
  createSettleRequest,
  CreateSettleRequestDataType,
  fetchSettleRequests,
  SettleRequestType
} from '../../api/settle-request';

export type useSettleRequestReturnType = UseQueryResult<SettleRequestType[]>;

export function useSettleRequests(): useSettleRequestReturnType {
  return useQuery<SettleRequestType[], APIErrorType>('settle-requests', fetchSettleRequests, {
    staleTime: 5 * 60 * 1000,
    retry: false
  });
}

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

  return useMutation<SettleRequestType, APIErrorType, CreateSettleRequestDataType>(
    createSettleRequest,
    {
      onSuccess: async () => {
        await queryClient.invalidateQueries('settle-requests');
      }
    }
  );
}
