package tech.easyflow.ai.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.stereotype.Service;
import tech.easyflow.ai.entity.PluginCategoryMapping;
import tech.easyflow.ai.mapper.PluginCategoryMappingMapper;
import tech.easyflow.ai.service.PluginVisibilityService;
import tech.easyflow.common.web.exceptions.BusinessException;
import tech.easyflow.system.entity.vo.RoleCategoryAccessSnapshot;
import tech.easyflow.system.service.CategoryPermissionService;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

@Service
public class PluginVisibilityServiceImpl implements PluginVisibilityService {

    @Resource
    private CategoryPermissionService categoryPermissionService;

    @Resource
    private PluginCategoryMappingMapper pluginCategoryMappingMapper;

    @Override
    public Set<BigInteger> getCurrentVisiblePluginIds() {
        RoleCategoryAccessSnapshot snapshot = categoryPermissionService.getCurrentAccess("PLUGIN");
        if (!snapshot.isRestricted() || CollectionUtil.isEmpty(snapshot.getCategoryIds())) {
            return Collections.emptySet();
        }
        QueryWrapper mappingWrapper = QueryWrapper.create()
                .select(PluginCategoryMapping::getPluginId)
                .in(PluginCategoryMapping::getCategoryId, snapshot.getCategoryIds());
        List<BigInteger> pluginIds = pluginCategoryMappingMapper.selectListByQueryAs(mappingWrapper, BigInteger.class);
        return new LinkedHashSet<>(pluginIds);
    }

    @Override
    public boolean canAccessPlugin(Long createdBy, BigInteger pluginId) {
        RoleCategoryAccessSnapshot snapshot = categoryPermissionService.getCurrentAccess("PLUGIN");
        if (!snapshot.isRestricted()) {
            return true;
        }
        if (createdBy != null && snapshot.getAccountId() != null
                && snapshot.getAccountId().equals(BigInteger.valueOf(createdBy))) {
            return true;
        }
        if (CollectionUtil.isEmpty(snapshot.getCategoryIds())) {
            return false;
        }
        QueryWrapper mappingWrapper = QueryWrapper.create()
                .select(PluginCategoryMapping::getPluginId)
                .eq(PluginCategoryMapping::getPluginId, pluginId)
                .in(PluginCategoryMapping::getCategoryId, snapshot.getCategoryIds());
        List<BigInteger> pluginIds = pluginCategoryMappingMapper.selectListByQueryAs(mappingWrapper, BigInteger.class);
        return CollectionUtil.isNotEmpty(pluginIds);
    }

    @Override
    public void assertPluginVisible(Long createdBy, BigInteger pluginId, String message) {
        if (!canAccessPlugin(createdBy, pluginId)) {
            throw new BusinessException(message == null ? "无权限访问该资源" : message);
        }
    }
}
