const AUTHENTICATED = 'authenticated';
const UNAUTHENTICATED = 'unauthenticated';

function isMenuItemVisible(itemControlMap, id) {
  const definedKeys = Object.keys(itemControlMap);
  if (definedKeys.includes(id)) {
    return Boolean(itemControlMap[id]);
  }
  return true;
}

const getFilteredMenuItems = (options) => (item) => {
  const { authenticated, isClientRender, itemControlMap } = options;
  const { authenticationState } = item;

  if (itemControlMap && !isMenuItemVisible(itemControlMap, item.id)) {
    return false;
  }

  if (authenticationState === AUTHENTICATED && !authenticated) {
    return false;
  }

  if (authenticationState === UNAUTHENTICATED && authenticated) {
    return false;
  }

  // Prevent authenticated items to be rendered on the first pass
  // https://reactjs.org/docs/react-dom.html#hydrate
  if (authenticationState === AUTHENTICATED && authenticated && !isClientRender) {
    return false;
  }

  return true;
};

export const filterMenuItems = (items, options = {}) => items.filter(getFilteredMenuItems(options));
