package com.neusoft.smart.pos.gateway.service;

import com.neusoft.smart.pos.gateway.service.feignService.RemoteUserService;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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 java.util.Arrays;
import java.util.stream.Collectors;

@Service
public class UserService implements UserDetailsService {

    RemoteUserService remoteUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.neusoft.smart.pos.dto.user.User user = remoteUserService.getUser(username);

        if (user != null) {
            return new User(user.getUsername(), user.getPassword(),
                    Arrays.stream(user.getRole().split(",")).map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
        } else {
            throw new UsernameNotFoundException("UserNotFound");
        }
    }
}
