package tech.easyflow.admin.controller.ai;

import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import tech.easyflow.ai.entity.DocumentCollection;
import tech.easyflow.ai.entity.DocumentCollectionCategory;
import tech.easyflow.ai.mapper.DocumentCollectionMapper;
import tech.easyflow.ai.service.DocumentCollectionCategoryService;
import tech.easyflow.common.annotation.UsePermission;
import tech.easyflow.common.domain.Result;
import tech.easyflow.common.web.controller.BaseCurdController;
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.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 *  控制层。
 *
 * @author wangGangQiang
 * @since 2026-01-23
 */
@RestController
@RequestMapping("/api/v1/documentCollectionCategory")
@UsePermission(moduleName = "/api/v1/documentCollection")
public class DocumentCollectionCategoryController extends BaseCurdController<DocumentCollectionCategoryService, DocumentCollectionCategory> {

    @Resource
    private DocumentCollectionMapper documentCollectionMapper;
    @Resource
    private CategoryPermissionService categoryPermissionService;

    public DocumentCollectionCategoryController(DocumentCollectionCategoryService service) {
        super(service);
    }

    @Override
    protected Result<?> onRemoveBefore(Collection<Serializable> ids) {
        ids.forEach(id -> {
            QueryWrapper queryWrapper = QueryWrapper.create().eq(DocumentCollection::getCategoryId, id);
            List<DocumentCollection> documentCollections = documentCollectionMapper.selectListByQuery(queryWrapper);
            if (!documentCollections.isEmpty()) {
                throw new BusinessException("请先删除该分类下的所有知识库");
            }
        });

        return super.onRemoveBefore(ids);
    }

    @GetMapping("visibleList")
    public Result<List<DocumentCollectionCategory>> visibleList(DocumentCollectionCategory entity, Boolean asTree, String sortKey, String sortType) {
        QueryWrapper queryWrapper = QueryWrapper.create(entity, buildOperators(entity));
        RoleCategoryAccessSnapshot access = categoryPermissionService.getCurrentAccess("KNOWLEDGE");
        if (access.isRestricted()) {
            if (access.getCategoryIds().isEmpty()) {
                return Result.ok(Collections.emptyList());
            }
            queryWrapper.in(DocumentCollectionCategory::getId, access.getCategoryIds());
        }
        queryWrapper.orderBy(buildOrderBy(sortKey, sortType, getDefaultOrderBy()));
        return Result.ok(service.list(queryWrapper));
    }
}
