package tech.easyflow.admin.controller.ai;

import org.springframework.web.bind.annotation.PostMapping;
import tech.easyflow.ai.entity.BotWorkflow;
import tech.easyflow.ai.entity.Workflow;
import tech.easyflow.ai.enums.PublishStatus;
import tech.easyflow.ai.permission.WorkflowReadAccessSnapshot;
import tech.easyflow.ai.permission.WorkflowVisibilityQueryHelper;
import tech.easyflow.ai.service.BotWorkflowService;
import tech.easyflow.ai.service.WorkflowService;
import tech.easyflow.common.annotation.UsePermission;
import tech.easyflow.common.domain.Result;
import tech.easyflow.common.tree.Tree;
import tech.easyflow.common.web.controller.BaseCurdController;
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.RestController;
import tech.easyflow.common.web.jsonbody.JsonBody;
import tech.easyflow.system.enums.CategoryResourceType;
import tech.easyflow.system.enums.ResourceAction;
import tech.easyflow.system.service.ResourceAccessService;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

/**
 *  控制层。
 *
 * @author michael
 * @since 2024-08-28
 */
@RestController
@RequestMapping("/api/v1/botWorkflow")
@UsePermission(moduleName = "/api/v1/bot")
public class BotWorkflowController extends BaseCurdController<BotWorkflowService, BotWorkflow> {
    @Resource
    private WorkflowService workflowService;
    @Resource
    private WorkflowVisibilityQueryHelper workflowVisibilityQueryHelper;
    @Resource
    private ResourceAccessService resourceAccessService;

    public BotWorkflowController(BotWorkflowService service) {
        super(service);
    }

    @GetMapping("list")
    @Override
    public Result<List<BotWorkflow>> list(BotWorkflow entity, Boolean asTree, String sortKey, String sortType) {
        QueryWrapper queryWrapper = QueryWrapper.create(entity, buildOperators(entity));
        queryWrapper.orderBy(buildOrderBy(sortKey, sortType, getDefaultOrderBy()));
        List<BotWorkflow> botWorkflows = service.getMapper().selectListWithRelationsByQuery(queryWrapper);
        List<BotWorkflow> visibleList = new ArrayList<>();
        WorkflowReadAccessSnapshot snapshot = workflowVisibilityQueryHelper.getCurrentReadSnapshot();
        for (BotWorkflow botWorkflow : botWorkflows) {
            Workflow workflow = botWorkflow.getWorkflow();
            if (workflow == null || workflowVisibilityQueryHelper.canRead(workflow, snapshot)) {
                visibleList.add(botWorkflow);
            }
        }
        List<BotWorkflow> list = Tree.tryToTree(visibleList, asTree);
        return Result.ok(list);
    }

    @PostMapping("updateBotWorkflowIds")
    public Result<?> save(@JsonBody("botId") BigInteger botId, @JsonBody("workflowIds") BigInteger [] workflowIds) {
        if (workflowIds != null) {
            for (BigInteger workflowId : workflowIds) {
                if (workflowId == null) {
                    continue;
                }
                Workflow workflow = workflowService.getById(workflowId);
                if (workflow == null) {
                    continue;
                }
                resourceAccessService.assertAccess(CategoryResourceType.WORKFLOW, workflow, ResourceAction.READ, "无权限绑定工作流");
                if (PublishStatus.from(workflow.getPublishStatus()) != PublishStatus.PUBLISHED) {
                    throw new tech.easyflow.common.web.exceptions.BusinessException("仅已发布工作流可被聊天助手引用");
                }
            }
        }
        service.saveBotAndWorkflowTool(botId, workflowIds);
        return Result.ok();
    }
}
