import { useQuery } from 'react-query';

import axios from 'axios';

import useCommunityFeature from 'src/hooks/useCommunityFeature';
import { CommunityFeature } from 'src/types/communityFeatures';

import { microloansKeys } from '../queries';
import { fetchActiveCollaboratorLoanPlan } from '../services/microloanService';

export function useActiveCollaboratorLoanPlan() {
  const canViewMicroloans = useCommunityFeature(
    CommunityFeature.VIEW_MICROLOANS,
  );
  return useQuery(
    microloansKeys.activeLoanPlan(),
    async () => {
      try {
        return await fetchActiveCollaboratorLoanPlan();
      } catch (error) {
        if (axios.isAxiosError(error) && error.response?.status === 404) {
          return null;
        }
        throw error;
      }
    },
    {
      staleTime: 30_000,
      retry: 1,
      enabled: canViewMicroloans,
    },
  );
}
