package com.njcn.rdms.module.system.api.permission;

import cn.hutool.core.collection.CollUtil;
import com.njcn.rdms.framework.common.pojo.CommonResult;
import com.njcn.rdms.module.system.api.permission.dto.UserVisibilityConfigRespDTO;
import com.njcn.rdms.module.system.dal.dataobject.permission.UserVisibilityConfigDO;
import com.njcn.rdms.module.system.service.dept.DeptService;
import com.njcn.rdms.module.system.service.permission.UserVisibilityConfigService;
import io.swagger.v3.oas.annotations.Hidden;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashSet;

import static com.njcn.rdms.framework.common.pojo.CommonResult.success;

/**
 * 用户可见性配置 RPC 接口实现。
 *
 * directionId → directionCode 的转换在 API 端完成，
 * 业务侧（rdms-project）不需要再 join system_dept。
 */
@RestController
@Validated
@Hidden
public class UserVisibilityConfigApiImpl implements UserVisibilityConfigApi {

    @Resource
    private UserVisibilityConfigService userVisibilityConfigService;
    @Resource
    private DeptService deptService;

    @Override
    public CommonResult<UserVisibilityConfigRespDTO> getConfig(Long userId) {
        UserVisibilityConfigDO cfg = userVisibilityConfigService.getByUserId(userId);
        if (cfg == null) {
            return success(null);
        }

        UserVisibilityConfigRespDTO dto = new UserVisibilityConfigRespDTO();
        dto.setType(cfg.getVisibilityType());

        if ("directions".equals(cfg.getVisibilityType())
                && CollUtil.isNotEmpty(cfg.getVisibleDirectionIds())) {
            // directionId → directionCode 转换：在 API 端做，避免 rdms-project 再 join system_dept
            dto.setDirectionCodes(deptService.listCodesByIds(cfg.getVisibleDirectionIds()));
        }
        if ("projects".equals(cfg.getVisibilityType())
                && CollUtil.isNotEmpty(cfg.getVisibleProjectIds())) {
            dto.setProjectIds(new HashSet<>(cfg.getVisibleProjectIds()));
        }
        return success(dto);
    }

}
