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

import com.zsc.edu.gateway.exception.StateException;
import com.zsc.edu.gateway.modules.system.entity.Menu;
import com.zsc.edu.gateway.modules.system.entity.RoleAuthority;
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.MenuRepository;
import com.zsc.edu.gateway.modules.system.repo.RoleAuthoritiesRepository;
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;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

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

    private final UserRepository userRepo;
//    private  final RoleAuthoritiesRepository roleAuthoritiesRepository;
    private  final AuthorityRepository authorityRepository;
    private final MenuRepository menuRepository;

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

//        List<RoleAuthority> roleAuthorities= roleAuthoritiesRepository.selectByRoleId(user.getRoleId());
//        user.role.authorities = authorityRepository.selectAuthoritiesByRoleId(user.getRoleId());
        List<Menu> menus = menuRepository.selectByRoleId(user.getRoleId());
        Set<String> permissions = menus.stream().map(Menu::getPermissions).collect(Collectors.toSet());
        return UserDetailsImpl.from(user, permissions);
    }
}
