import { useMutation, useQueryClient } from 'react-query';

import { type WebAcceptanceClientContext } from 'src/utils/webClientContext';

import { invalidateMicroloansAfterAcceptOffer } from '../queries';
import { acceptCollaboratorOffer } from '../services/microloanService';
import { currencyToCollaboratorMinorUnits } from '../utils/collaboratorAmount';

export function useAcceptCollaboratorOffer(offerId: string) {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (params: {
      amountMxn: number;
      installmentsChosen: number;
      phoneNumber: string;
      loanReason: string;
      loanReasonComment?: string;
      deviceMetadata: WebAcceptanceClientContext;
      bankAccountNumber?: string;
      bankName?: string;
    }) => {
      const trimmedComment = params.loanReasonComment?.trim();
      return acceptCollaboratorOffer(offerId, {
        totalAmount: currencyToCollaboratorMinorUnits(params.amountMxn),
        installmentsChosen: params.installmentsChosen,
        phoneNumber: params.phoneNumber,
        loanReason: params.loanReason,
        ...(trimmedComment ? { loanReasonComment: trimmedComment } : {}),
        ...(params.bankAccountNumber !== undefined
          ? { bankAccountNumber: params.bankAccountNumber }
          : {}),
        ...(params.bankName ? { bankName: params.bankName } : {}),
        deviceMetadata: params.deviceMetadata,
      });
    },
    onSuccess: () => {
      invalidateMicroloansAfterAcceptOffer(queryClient);
    },
  });
}
