package tech.easyflow.ai.permission;

import org.springframework.stereotype.Component;
import tech.easyflow.ai.entity.DocumentChunk;
import tech.easyflow.ai.entity.DocumentCollection;
import tech.easyflow.ai.service.DocumentChunkService;
import tech.easyflow.ai.service.DocumentCollectionService;
import tech.easyflow.common.web.exceptions.BusinessException;
import tech.easyflow.system.enums.CategoryResourceType;
import tech.easyflow.system.enums.ResourceLookup;
import tech.easyflow.system.permission.resource.ResolvedResourceAccess;
import tech.easyflow.system.permission.resource.ResourceAccessResolver;

import javax.annotation.Resource;

@Component
public class DocumentChunkIdKnowledgeResourceAccessResolver implements ResourceAccessResolver {

    @Resource
    private DocumentChunkService documentChunkService;

    @Resource
    private DocumentCollectionService documentCollectionService;

    @Override
    public boolean supports(CategoryResourceType resourceType, ResourceLookup lookup) {
        return CategoryResourceType.KNOWLEDGE == resourceType && ResourceLookup.DOCUMENT_CHUNK_ID == lookup;
    }

    @Override
    public ResolvedResourceAccess resolve(Object identifier) {
        if (identifier == null) {
            throw new BusinessException("文档分段不存在");
        }
        DocumentChunk documentChunk = documentChunkService.getById(String.valueOf(identifier));
        if (documentChunk == null) {
            throw new BusinessException("文档分段不存在");
        }
        DocumentCollection collection = documentCollectionService.getById(documentChunk.getDocumentCollectionId());
        if (collection == null) {
            throw new BusinessException("知识库不存在");
        }
        return new ResolvedResourceAccess(collection, null);
    }
}
