const ALREADY_EXIST_EMAIL = 'fe@wickes.co.uk';
const ALREADY_EXIST_EMAIL_IN_ANOTHER_ACCOUNT = 'mad.fe@wickes.co.uk';
const ALREADY_EXIST_EMAIL_AFTER_CHECK = 'fe.af@wickes.co.uk';
const ALREADY_EXIST_EMAIL_IN_ANOTHER_ACCOUNT_AFTER_CHECK = 'mad.fe.af@wickes.co.uk';
const MEMBERS_LIMIT = 10;

function returnExistEmailError() {
  return {
    message: 'Member already exists'
  };
}

function returnExistEmailInAnotherAccountError() {
  return {
    message: 'Member already exists in another Business Account'
  };
}

function initAccountMembersFunctionality() {
  if (!$('.add-members').length) {
    return;
  }

  Wick.AccountMembers.init({membersLimit: MEMBERS_LIMIT});

  $(window).on(Wick.AccountMembers.VERIFY_EMAIL_EVENT, function (e) {
    setTimeout(() => {
      if (e.detail.payload.email === ALREADY_EXIST_EMAIL) {
        e.detail.reject(returnExistEmailError());
      } else if (e.detail.payload.email === ALREADY_EXIST_EMAIL_IN_ANOTHER_ACCOUNT) {
        e.detail.reject(returnExistEmailInAnotherAccountError());
      } else {
        e.detail.resolve();
      }
    }, 1000);
  });

  $(window).on(Wick.AccountMembers.VERIFY_EMAILS_EVENT, function (e) {
    setTimeout(() => {
      const emails = e.detail.payload.emails;
      const isErrors = emails.some(
        email => email === ALREADY_EXIST_EMAIL_AFTER_CHECK
        || email === ALREADY_EXIST_EMAIL_IN_ANOTHER_ACCOUNT_AFTER_CHECK
      );
      if (isErrors) {
        e.detail.reject();
      } else {
        e.detail.resolve();
      }
    }, 1000);
  });
}

$(document).ready(function () {
  initAccountMembersFunctionality();
});
