/* (C) 2022 YiRing, Inc. */
package com.yiring.auth.config;

import cn.dev33.satoken.stp.StpInterface;
import com.yiring.auth.domain.permission.Permission;
import com.yiring.auth.domain.role.Role;
import com.yiring.auth.domain.user.User;
import com.yiring.auth.domain.user.UserRepository;
import com.yiring.common.utils.RepositoryUtil;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 获取登录用户权限信息实现
 *
 * @author Jim
 * @version 0.1
 * 2022/3/25 9:37
 */

@Transactional(readOnly = true)
@Component
@RequiredArgsConstructor
public class StpInterfaceImpl implements StpInterface {

    final UserRepository userRepository;

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        User user = getUser(loginId);
        return user
            .getRoles()
            .stream()
            .map(Role::getPermissions)
            .flatMap(Set::stream)
            .distinct()
            .map(Permission::getUid)
            .collect(Collectors.toList());
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        User user = getUser(loginId);
        return user.getRoles().stream().map(Role::getUid).collect(Collectors.toList());
    }

    /**
     * 根据 id 获取用户信息
     *
     * @param loginId 登录 ID
     * @return 用户信息
     */
    public User getUser(Object loginId) {
        String id = Objects.toString(loginId);
        return RepositoryUtil.find(userRepository, id, "Code.1000");
    }
}
