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 { fetchCollaboratorPayments } from '../services/microloanService';
import { normalizeCollaboratorPaymentsResponse } from '../utils/normalizeCollaboratorPayments';

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