var Wick = Wick || {};
Wick.PersonalDetailsData = (function(){
  return {
    success: {
      globalMessage: {
        status: 'success',
        message: 'Your profile has been updated',
      },
      fieldErrors: null,
    },
    validationError: {
      globalMessage: {
        status: 'error',
        message: 'Please correct the errors below.',
      },
      fieldErrors: [
        { field: 'email', message: 'Please enter your email' },
      ],
    },
    serverError: {
      globalMessage: {
        status: 'error',
        message: 'Sorry, we were unable to update your personal details, please try again',
      },
      fieldErrors: null,
    },
  }
})()

function getResponseBasedOnField(personalDetails) {
  const personalDetailsObject = personalDetails.reduce((acc, { name, value }) => {
    acc[name] = value;
    return acc;
  }, {});

  const { firstName, email } = personalDetailsObject;
  const isValidationError = email === 'test@gmail.com';
  const isServerError = firstName === 'server_error';

  if (isValidationError) {
    return { success: false, response: Wick.PersonalDetailsData.validationError };
  }

  if (isServerError) {
    return { success: false, response: Wick.PersonalDetailsData.serverError };
  }

  return { success: true, response: Wick.PersonalDetailsData.success };
}

function initPersonalDetails() {
  if (!Wick?.PersonalDetails?.UPDATE_PERSONAL_DETAILS_EVENT) {
    return;
  }

  $(window).on(Wick.PersonalDetails.UPDATE_PERSONAL_DETAILS_EVENT, function ({ detail: { resolve, reject } }) {
    setTimeout(() => {
      const personalDetails = Wick.LeaveEvent.getState(Wick.PersonalDetails.el.userForm);

      const { success, response } = getResponseBasedOnField(personalDetails);

      if (success) {
        return resolve(response);
      } else {
        return reject(response);
      }
    }, 500);
  });
}

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