package org.ros.chatto.security;

import java.util.Set;

import org.ros.chatto.model.ChatUser;
import org.ros.chatto.model.UserRole;
import org.ros.chatto.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
@RequiredArgsConstructor
public class MyUserDetailsService implements UserDetailsService {

	@Autowired
	private final UserService userService;

	@Override
	public UserDetails loadUserByUsername(final String username) {
		log.trace("User Details - loading with username: {}", username);
		ChatUser user = userService.getUserWithRole(username);

		if (user == null) {
			log.warn("Request for unknown user {}", username);
			throw new UsernameNotFoundException(username);
		}

		Set<UserRole> userRoles = user.getUserRoles();

		return User.withUsername(user.getUserName())
				.password(user.getPassword())
				.roles(userRoles.stream().map(ur -> ur.getRole().getName())
						.toArray(size -> new String[size]))
				.build();
	}
}
