package cn.reghao.bnt.web.devops.app.service;

import cn.reghao.bnt.web.admin.model.constant.RoleType;
import cn.reghao.bnt.web.admin.model.po.Role;
import cn.reghao.bnt.web.admin.model.po.User;
import cn.reghao.bnt.web.admin.service.RoleService;
import cn.reghao.bnt.web.admin.service.UserContext;
import cn.reghao.bnt.web.devops.builder.model.constant.EnvType;
import org.springframework.stereotype.Service;

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

/**
 * @author reghao
 * @date 2024-02-04 15:15:38
 */
@Service
public class PermissionCheck {
    private final RoleService roleService;

    public PermissionCheck(RoleService roleService) {
        this.roleService = roleService;
    }

    public User check(String env) throws Exception {
        User user = UserContext.getUser();
        if (user == null) {
            throw new Exception("未登录");
        } else {
            Set<String> userRoles = roleService.getRolesByUser(user.getId()).stream()
                    .map(Role::getName)
                    .collect(Collectors.toSet());
            boolean isAdmin = userRoles.contains(RoleType.ROLE_DEVOPS_ADMIN.name());
            if (EnvType.prod.name().equals(env) && !isAdmin) {
                throw new Exception("没有权限");
            }
        }

        return user;
    }
}
