package tech.easyflow.usercenter.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.WorkflowCategory;
import tech.easyflow.ai.service.WorkflowCategoryService;
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.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * 工作流分类
 *
 * @author ArkLight
 * @since 2025-12-11
 */
@RestController
@RequestMapping("/userCenter/workflowCategory")
@UsePermission(moduleName = "/api/v1/workflow")
public class UcWorkflowCategoryController extends BaseCurdController<WorkflowCategoryService, WorkflowCategory> {
    @Resource
    private CategoryPermissionService categoryPermissionService;

    public UcWorkflowCategoryController(WorkflowCategoryService service) {
        super(service);
    }

    @Override
    protected Result<?> onSaveOrUpdateBefore(WorkflowCategory entity, boolean isSave) {
        return Result.fail("-");
    }

    @Override
    protected Result<?> onRemoveBefore(Collection<Serializable> ids) {
        return Result.fail("-");
    }

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