package tech.easyflow.admin.controller.ai;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import tech.easyflow.ai.entity.PluginCategory;
import tech.easyflow.ai.service.PluginCategoryService;
import tech.easyflow.common.annotation.UsePermission;
import tech.easyflow.common.domain.Result;
import tech.easyflow.common.web.controller.BaseCurdController;
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.List;

/**
 *  控制层。
 *
 * @author wangGangQiang
 * @since 2025-05-21
 */
@RestController
@RequestMapping("/api/v1/pluginCategory")
@UsePermission(moduleName = "/api/v1/plugin")
public class PluginCategoryController extends BaseCurdController<PluginCategoryService, PluginCategory> {
    public PluginCategoryController(PluginCategoryService service) {
        super(service);
    }

    @Resource
    private PluginCategoryService pluginCategoryService;
    @Resource
    private CategoryPermissionService categoryPermissionService;

    @GetMapping("/doRemoveCategory")
    @SaCheckPermission("/api/v1/plugin/remove")
    public Result<Boolean> doRemoveCategory(@RequestParam("id") BigInteger id){

        return Result.ok(pluginCategoryService.doRemoveCategory(id));
    }

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