import { getDataFromCollection } from '../../../../../../db';

export default async function getReceiveAddressAndContactForContactsPayment({
  sendingAmountSat,
  selectedContact,
  myProfileMessage = '',
  payingContactMessage = '',
  onlyGetContact = false,
  prefetchedDoc = null,
}) {
  try {
    let receiveAddress;
    let retrivedContact;
    let message = '';

    if (selectedContact.isLNURL) {
      receiveAddress = selectedContact.receiveAddress;
      retrivedContact = selectedContact;
    } else if (prefetchedDoc) {
      retrivedContact = prefetchedDoc;

      if (onlyGetContact)
        return { didWork: true, receiveAddress: '', retrivedContact };

      if (retrivedContact?.contacts?.myProfile?.sparkAddress) {
        if (payingContactMessage?.usingTranslation) {
          message = retrivedContact.isUsingNewNotifications
            ? JSON.stringify({
                name: payingContactMessage.name,
                translation: 'contacts.sendAndRequestPage.contactMessage',
              })
            : `${payingContactMessage.name} paid you`;
        } else {
          message = payingContactMessage;
        }

        receiveAddress = retrivedContact?.contacts?.myProfile?.sparkAddress;
      } else throw new Error('errormessages.legacyContactError');
    } else {
      retrivedContact = await getDataFromCollection(
        'blitzWalletUsers',
        selectedContact.uuid,
      );

      if (!retrivedContact) throw new Error('errormessages.fullDeeplinkError');

      if (onlyGetContact)
        return { didWork: true, receiveAddress: '', retrivedContact };

      if (retrivedContact?.contacts?.myProfile?.sparkAddress) {
        if (payingContactMessage?.usingTranslation) {
          message = retrivedContact.isUsingNewNotifications
            ? JSON.stringify({
                name: payingContactMessage.name,
                translation: 'contacts.sendAndRequestPage.contactMessage',
              })
            : `${payingContactMessage.name} paid you`;
        } else {
          message = payingContactMessage;
        }

        receiveAddress = retrivedContact?.contacts?.myProfile?.sparkAddress;
      } else throw new Error('errormessages.legacyContactError');
    }

    return {
      didWork: true,
      receiveAddress,
      retrivedContact,
      formattedPayingContactMessage: message,
    };
  } catch (err) {
    console.log('error getting receive address for contact payment');
    return { didWork: false, error: err.message };
  }
}
