export const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
export const DISALLOWED_SPECIAL_CHARS = /:|\.|\/|;/;

const RECAPTCHA_SITE_KEY = process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY || '';

export const removeQueryParams = () => {
  var newURL = location.href.split('?')[0];
  window.history.pushState('object', document.title, newURL);
};

/**
 *
 * @param action Name of the action, may only contain alphanumeric characters and slashes, e.g. "contact_form". Must not be user specific.
 * @returns Recaptcha token
 */
export const getRecaptchaToken = async (action: string = 'login') => {
  return new Promise((resolve, reject) => {
    if (!RECAPTCHA_SITE_KEY) {
      reject('Recaptcha site key not found');
    }
    try {
      grecaptcha.ready(async () => {
        const token = await grecaptcha.execute(RECAPTCHA_SITE_KEY, { action });
        resolve(token);
      });
    } catch (error) {
      reject(error);
    }
  });
};

export const checkPassword = (password: string) => {
  if (!password) {
    return 'Required';
  } else if (password.length < 8) {
    return 'Password too short (> 8 characters)';
  } else if (password.length > 100) {
    return 'Password too long (< 100 characters)';
  } else if (!/[A-Z]/.test(password)) {
    return 'Password must have uppercase letter';
  } else if (!/[a-z]/.test(password)) {
    return 'Password must have lowercase letter';
  } else if (!/[0-9]/.test(password)) {
    return 'Password must have number';
  }
  return null;
};
