class AxonServerStandardConfiguration {

    @Bean
    @ConditionalOnMissingBean(UserControllerFacade.class)
    public UserControllerFacade userControllerFacade(UserController userController,
                                                     ApplicationEventPublisher eventPublisher) {
        return new UserControllerFacade() {
            @Override
            public void updateUser(String userName, String password, Set<UserRole> roles) {
                validateContexts(roles);
                User updatedUser = userController.updateUser(userName, password, roles);
                eventPublisher.publishEvent(new UserEvents.UserUpdated(updatedUser, false));

            }

            private void validateContexts(Set<UserRole> roles) {
                if (roles == null) {
                    return;
                }
                if (roles.stream().anyMatch(userRole -> !validContext(userRole.getContext()))) {
                    throw new MessagingPlatformException(ErrorCode.CONTEXT_NOT_FOUND,
                                                         "Only specify context default for standard edition");
                }
            }

            private boolean validContext(String context) {
                return context == null || context.equals(Topology.DEFAULT_CONTEXT) || context.equals("*");
            }

            @Override
            public List<User> getUsers() {
                return userController.getUsers();
            }

            @Override
            public void deleteUser(String name) {
                userController.deleteUser(name);
                eventPublisher.publishEvent(new UserEvents.UserDeleted(name, false));
            }
        };
    }

}