package tech.easyflow.admin.controller.ai;

import org.springframework.web.bind.annotation.PostMapping;
import tech.easyflow.ai.dto.BotKnowledgeBindingRequest;
import tech.easyflow.ai.entity.BotDocumentCollection;
import tech.easyflow.ai.entity.DocumentCollection;
import tech.easyflow.ai.enums.PublishStatus;
import tech.easyflow.ai.permission.KnowledgeReadAccessSnapshot;
import tech.easyflow.ai.permission.KnowledgeVisibilityQueryHelper;
import tech.easyflow.ai.service.BotDocumentCollectionService;
import tech.easyflow.ai.service.DocumentCollectionService;
import tech.easyflow.common.annotation.UsePermission;
import tech.easyflow.common.domain.Result;
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 javax.annotation.Resource;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

/**
 * 控制层。
 *
 * @author michael
 * @since 2024-08-28
 */
@RestController
@RequestMapping("/api/v1/botKnowledge")
@UsePermission(moduleName = "/api/v1/bot")
public class BotDocumentCollectionController extends BaseCurdController<BotDocumentCollectionService, BotDocumentCollection> {
    @Resource
    private DocumentCollectionService documentCollectionService;
    @Resource
    private KnowledgeVisibilityQueryHelper knowledgeVisibilityQueryHelper;
    @Resource
    private ResourceAccessService resourceAccessService;

    public BotDocumentCollectionController(BotDocumentCollectionService service) {
        super(service);
    }

    @GetMapping("list")
    @Override
    public Result<List<BotDocumentCollection>> list(BotDocumentCollection entity, Boolean asTree, String sortKey, String sortType) {
        QueryWrapper queryWrapper = QueryWrapper.create(entity, buildOperators(entity));
        queryWrapper.orderBy(buildOrderBy(sortKey, sortType, getDefaultOrderBy()));
        List<BotDocumentCollection> botDocumentCollections = service.getMapper().selectListWithRelationsByQuery(queryWrapper);
        List<BotDocumentCollection> visibleList = new ArrayList<>();
        KnowledgeReadAccessSnapshot snapshot = knowledgeVisibilityQueryHelper.getCurrentReadSnapshot();
        for (BotDocumentCollection relation : botDocumentCollections) {
            DocumentCollection knowledge = relation.getKnowledge();
            if (knowledge == null || knowledgeVisibilityQueryHelper.canRead(knowledge, snapshot)) {
                visibleList.add(relation);
            }
        }
        return Result.ok(visibleList);
    }

    @PostMapping("updateBotKnowledgeIds")
    public Result<?> save(@JsonBody("botId") BigInteger botId,
                          @JsonBody("knowledgeBindings") List<BotKnowledgeBindingRequest> knowledgeBindings) {
         if (knowledgeBindings != null) {
             for (BotKnowledgeBindingRequest binding : knowledgeBindings) {
                 if (binding == null || binding.getKnowledgeId() == null) {
                     continue;
                 }
                 DocumentCollection collection = documentCollectionService.getById(binding.getKnowledgeId());
                 if (collection == null) {
                     continue;
                 }
                 resourceAccessService.assertAccess(CategoryResourceType.KNOWLEDGE, collection, ResourceAction.READ, "无权限绑定知识库");
                 if (PublishStatus.from(collection.getPublishStatus()) != PublishStatus.PUBLISHED) {
                     throw new tech.easyflow.common.web.exceptions.BusinessException("仅已发布知识库可被聊天助手引用");
                 }
             }
         }
         service.saveBotAndKnowledge(botId, knowledgeBindings);
        return Result.ok();
    }
}
