/* global window */

import { createFactory } from 'react';
import { contains } from 'ramda';

const checkAuthorization = (user, roles) => {
  const userRole = user.profiles[0];
  const userOrgType = userRole.organization.type.key;

  if (!roles) {
    return true;
  }

  const role = roles[userRole.key];

  if (role && contains(userOrgType, role)) {
    return true;
  }

  return false;
};

const authorization = roles => ({
  roles,
  authorize(WrappedComponent) {
    const loggedUser = JSON.parse(window.localStorage.getItem('loggedUser'));

    if (!loggedUser) {
      return (props) => {
        props.router.push('/login');
        return null;
      };
    }

    const factory = createFactory(WrappedComponent);
    const isAuthorized = checkAuthorization(loggedUser, roles);

    if (!isAuthorized) {
      return (props) => {
        props.router.push('/404');
        return null;
      };
    }

    const Component = props => factory(props);
    return Component;
  },
});

export default authorization;
