package com.zioinfo.hrm.uiws.system.service;

import com.zioinfo.hrm.uiws.common.UiwsApiException;
import com.zioinfo.hrm.uiws.common.UiwsErrorCode;
import com.zioinfo.hrm.uiws.system.dto.DeptUserRoleDto;
import com.zioinfo.hrm.uiws.system.dto.PageResponse;
import com.zioinfo.hrm.uiws.system.mapper.DeptMapper;
import com.zioinfo.hrm.uiws.system.mapper.DeptRoleMapper;
import com.zioinfo.hrm.uiws.system.mapper.SysUserMapper;
import com.zioinfo.hrm.uiws.system.model.SysUser;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 2.2 부서권한(dept-role). 부서 단위 권한 부여/삭제.
 * 조회는 부서 소속 사용자 목록에 부서-권한(roleIds)을 동일하게 부여(권한이 부서로 결정되는 모델).
 */
@Service
@RequiredArgsConstructor
public class DeptRoleService {

    private final DeptRoleMapper deptRoleMapper;
    private final DeptMapper deptMapper;
    private final SysUserMapper userMapper;

    @Transactional(readOnly = true)
    public PageResponse<DeptUserRoleDto> listDeptUsers(String deptId, int page, int size) {
        ensureDept(deptId);
        List<String> roleIds = deptRoleMapper.findRoleIdsByDeptId(deptId);
        List<SysUser> users = userMapper.search(null, deptId, page * size, size);
        List<DeptUserRoleDto> content = users.stream()
                .map(u -> new DeptUserRoleDto(u.getUserId(), u.getUserNm(), roleIds)).toList();
        return PageResponse.of(content, userMapper.countSearch(null, deptId), page, size);
    }

    @Transactional
    public void grant(String deptId, List<String> roleIds) {
        ensureDept(deptId);
        String actor = SysActor.id();
        for (String roleId : roleIds) {
            deptRoleMapper.insert(deptId, roleId, actor);
        }
    }

    @Transactional
    public void revoke(String deptId, List<String> roleIds) {
        ensureDept(deptId);
        for (String roleId : roleIds) {
            deptRoleMapper.delete(deptId, roleId);
        }
    }

    private void ensureDept(String deptId) {
        if (!deptMapper.existsById(deptId)) {
            throw new UiwsApiException(UiwsErrorCode.DEPT_NOT_FOUND);
        }
    }
}
