import { useQuery } from 'react-query';

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

import { microloansKeys } from '../queries';
import { fetchCollaboratorFinishedLoans } from '../services/finishedLoans';
import { type FinishedLoan } from '../types';

function compareClosingDateDesc(a: FinishedLoan, b: FinishedLoan): number {
  if (a.closeDate === b.closeDate) {
    return 0;
  }
  return a.closeDate > b.closeDate ? -1 : 1;
}

export function useCollaboratorFinishedLoans() {
  const canViewMicroloans = useCommunityFeature(
    CommunityFeature.VIEW_MICROLOANS,
  );

  return useQuery({
    queryKey: microloansKeys.finishedLoans(),
    queryFn: fetchCollaboratorFinishedLoans,
    staleTime: 30_000,
    retry: 1,
    enabled: canViewMicroloans,
    select: (data: FinishedLoan[]) => [...data].sort(compareClosingDateDesc),
  });
}
