package tech.easyflow.system.service.impl;

import tech.easyflow.system.entity.SysDept;
import tech.easyflow.system.mapper.SysDeptMapper;
import tech.easyflow.system.service.SysDeptService;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * 部门表 服务层实现。
 *
 * @author ArkLight
 * @since 2025-03-14
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {

    @Override
    public Set<BigInteger> getSelfAndAncestorDeptIds(BigInteger currentDeptId) {
        if (currentDeptId == null) {
            return Collections.emptySet();
        }
        SysDept currentDept = getById(currentDeptId);
        if (currentDept == null) {
            return Collections.emptySet();
        }
        Set<BigInteger> deptIds = new LinkedHashSet<>();
        String ancestors = currentDept.getAncestors();
        if (ancestors != null && !ancestors.isBlank()) {
            String[] items = ancestors.split(",");
            for (String item : items) {
                if (item == null || item.isBlank()) {
                    continue;
                }
                BigInteger deptId = new BigInteger(item.trim());
                if (BigInteger.ZERO.equals(deptId)) {
                    continue;
                }
                deptIds.add(deptId);
            }
        }
        deptIds.add(currentDeptId);
        return deptIds;
    }

    @Override
    public boolean canUserAccessDeptScopedResource(BigInteger currentDeptId, BigInteger resourceDeptId) {
        if (currentDeptId == null || resourceDeptId == null) {
            return false;
        }
        return getSelfAndAncestorDeptIds(currentDeptId).contains(resourceDeptId);
    }
}
