/* eslint no-console: "off" */

const { assign, keys } = Object;

const normalizeRoles = (profiles) => {
  const roleKeys = keys(profiles);

  if (roleKeys.length === 0) {
    console.warn('[Authorize Warning] You need to specify at least one profile');
    return arg => arg;
  }

  if (roleKeys.length === 1) {
    return profiles[roleKeys[0]].roles;
  }

  const roles = profiles.reduce((result, profile) => {
    const profileRoles = keys(profile.roles).reduce((r, key) => {
      const role = r;

      if (result[key]) {
        role[key] = result[key].concat(profile.roles[key]);
      } else {
        role[key] = profile.roles[key];
      }

      return role;
    }, {});

    return assign(
      {},
      result,
      profileRoles,
    );
  }, {});

  return roles;
};

export default normalizeRoles;
