package tech.easyflow.admin.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tech.easyflow.common.domain.Result;
import tech.easyflow.common.satoken.util.SaTokenUtil;
import tech.easyflow.common.web.exceptions.BusinessException;
import tech.easyflow.common.web.jsonbody.JsonBody;
import tech.easyflow.system.entity.vo.SysRoleCategoryScopeDetailVo;
import tech.easyflow.system.service.CategoryPermissionService;
import tech.easyflow.system.service.SysRoleCategoryScopeService;

import javax.annotation.Resource;
import java.math.BigInteger;

@RestController
@RequestMapping("/api/v1/sysRoleCategoryScope")
public class SysRoleCategoryScopeController {

    @Resource
    private SysRoleCategoryScopeService sysRoleCategoryScopeService;

    @Resource
    private CategoryPermissionService categoryPermissionService;

    @GetMapping("/detail")
    @SaCheckPermission("/api/v1/sysRole/query")
    public Result<SysRoleCategoryScopeDetailVo> detail(BigInteger roleId) {
        SysRoleCategoryScopeDetailVo detail = sysRoleCategoryScopeService.getRoleScopeDetail(roleId);
        detail.setEditable(categoryPermissionService.isCurrentSuperAdmin());
        return Result.ok(detail);
    }

    @PostMapping("/save")
    @SaCheckPermission("/api/v1/sysRole/save")
    public Result<Void> save(@JsonBody SysRoleCategoryScopeDetailVo request) {
        assertSuperAdmin();
        if (request == null || request.getRoleId() == null) {
            throw new BusinessException("角色ID不能为空");
        }
        BigInteger operatorId = SaTokenUtil.getLoginAccount().getId();
        sysRoleCategoryScopeService.saveRoleScopes(request.getRoleId(), request.getScopes(), operatorId);
        return Result.ok();
    }

    private void assertSuperAdmin() {
        if (!categoryPermissionService.isCurrentSuperAdmin()) {
            throw new BusinessException("仅超级管理员可配置分类权限");
        }
    }
}
