package com.zsc.edu.gateway.framework.security;

import com.zsc.edu.gateway.exception.StateException;
import com.zsc.edu.gateway.modules.system.entity.User;
import com.zsc.edu.gateway.modules.system.repo.AuthorityRepository;
import com.zsc.edu.gateway.modules.system.repo.UserRepository;
import lombok.AllArgsConstructor;
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 org.springframework.transaction.annotation.Transactional;

/**
 * @author harry_yao
 */
@AllArgsConstructor
@Service
public class JpaUserDetailsServiceImpl implements UserDetailsService {

    private final UserRepository userRepo;
    private  final AuthorityRepository authorityRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepo.selectByUsername(username);
        if (!user.getEnableState()) {
            throw new StateException("用户 '" + username + "' 已被禁用！请联系管理员");
        }

        user.role.authorities = authorityRepository.selectAuthoritiesByRoleId(user.getRoleId());
//        =roleAuthorities.stream()
//                .map(i -> Authority.valueOf(i.getAuthority()))
//                .collect(Collectors.toSet());



//                .orElseThrow(() ->
//            new UsernameNotFoundException("用户 '" + username + "' 不存在!")
//        );
//        user.getIdentities().stream().filter(identity -> identity.role.enableState == EnableState.启用)
//            .forEach(identity -> Hibernate.initialize(identity.role.roleAuthorities));
        return UserDetailsImpl.from(user);
    }
}
