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 { fetchActiveCollaboratorOffer } from '../services/microloanService';
import { type LoanOffer } from '../types';
import { mapCollaboratorOfferToLoanOffer } from '../utils/mapCollaboratorOfferToLoanOffer';

export async function getLoanOffer(): Promise<LoanOffer | undefined> {
  try {
    const dto = await fetchActiveCollaboratorOffer();
    return mapCollaboratorOfferToLoanOffer(dto);
  } catch (error) {
    if (axios.isAxiosError(error) && error.response?.status === 404) {
      return undefined;
    }
    throw error;
  }
}

export type UseGetLoanOfferResult = {
  loanOffer: LoanOffer | undefined;
  isLoading: boolean;
  isError: boolean;
  error: unknown;
  retry: () => void;
};

export const useGetLoanOffer = (): UseGetLoanOfferResult => {
  const canViewMicroloans = useCommunityFeature(
    CommunityFeature.VIEW_MICROLOANS,
  );
  const { data, isLoading, isError, error, refetch } = useQuery(
    microloansKeys.loanOffer(),
    getLoanOffer,
    {
      staleTime: Infinity,
      retry: 1,
      enabled: canViewMicroloans,
    },
  );

  return {
    loanOffer: data,
    isLoading,
    isError,
    error,
    retry: refetch,
  };
};
