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.ResourceCategory;
import tech.easyflow.ai.service.ResourceCategoryService;
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.util.Collections;
import java.util.List;

/**
 * 素材分类
 */
@RestController
@RequestMapping("/api/v1/resourceCategory")
@UsePermission(moduleName = "/api/v1/resource")
public class ResourceCategoryController extends BaseCurdController<ResourceCategoryService, ResourceCategory> {
    @Resource
    private CategoryPermissionService categoryPermissionService;

    public ResourceCategoryController(ResourceCategoryService service) {
        super(service);
    }

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