package com.lideeyunji.service.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.lideeyunji.service.system.entity.OAuth2ClientDO;
import com.lideeyunji.service.system.entity.RoleOAuth2ClientDO;
import com.lideeyunji.service.system.mapper.RoleOAuth2ClientMapper;
import com.lideeyunji.service.system.service.IClientPermissionService;
import com.lideeyunji.service.system.service.IOAuth2ClientService;
import com.lideeyunji.service.system.service.IRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.lideeyunji.tool.framework.common.util.collection.CollectionUtils.convertSet;

@Service
@Validated
@Slf4j
public class ClientPermissionServiceImpl implements IClientPermissionService {
    @Resource
    private RoleOAuth2ClientMapper roleOAuth2ClientMapper;
    @Resource
    private IRoleService roleService;

    @Lazy
    @Resource
    private IOAuth2ClientService ioAuth2ClientService;

    public Set<Long> getRoleClientListByRoleId(Collection<Long> roleIds) {
        if (CollUtil.isEmpty(roleIds)) {
            return Collections.emptySet();
        }

        if (roleService.hasAnySuperAdmin(roleIds)) {
            List<OAuth2ClientDO> allEnableClient = ioAuth2ClientService.getAllEnableClient();
            return Optional.ofNullable(allEnableClient)
                    .map(all -> all.stream()
                            .map(OAuth2ClientDO::getId)
                            .collect(Collectors.toSet()))
                    .orElse(new HashSet<>());
        }

        return convertSet(roleOAuth2ClientMapper.selectListByRoleId(roleIds),
                RoleOAuth2ClientDO::getOauthClientId);
    }
}
