package com.ga.api.service.system;

import com.ga.common.exception.BizException;
import com.ga.common.exception.ErrorCode;
import com.ga.core.mapper.user.RoleMapper;
import com.ga.core.vo.user.RoleVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class RoleService {

    private final RoleMapper mapper;

    @Transactional(readOnly = true)
    public List<RoleVO> list() {
        return mapper.selectAll();
    }

    @Transactional(readOnly = true)
    public RoleVO detail(Long roleId) {
        RoleVO vo = mapper.selectById(roleId);
        if (vo == null) throw new BizException(ErrorCode.NOT_FOUND);
        return vo;
    }

    @Transactional(readOnly = true)
    public List<Map<String, Object>> permissions(Long roleId) {
        return mapper.selectRolePermissions(roleId);
    }

    @Transactional
    public Long create(RoleVO vo) {
        mapper.insert(vo);
        return vo.getRoleId();
    }

    @Transactional
    public void update(Long roleId, RoleVO vo) {
        if (mapper.selectById(roleId) == null) throw new BizException(ErrorCode.NOT_FOUND);
        vo.setRoleId(roleId);
        mapper.update(vo);
    }

    @Transactional
    public void delete(Long roleId) {
        if (mapper.selectById(roleId) == null) throw new BizException(ErrorCode.NOT_FOUND);
        mapper.deleteById(roleId);
    }

    @Transactional
    public void savePermissions(Long roleId, List<Map<String, Object>> permissions) {
        mapper.deleteRolePermissions(roleId);
        for (Map<String, Object> p : permissions) {
            Long menuId = ((Number) p.get("menuId")).longValue();
            String permCode = (String) p.get("permCode");
            String isGranted = (String) p.getOrDefault("isGranted", "Y");
            mapper.insertRolePermission(roleId, menuId, permCode, isGranted);
        }
    }
}
