package tech.easyflow.ai.permission;

import org.springframework.stereotype.Component;
import tech.easyflow.ai.entity.DocumentCollection;
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 KnowledgeIdOrSlugResourceAccessResolver implements ResourceAccessResolver {

    @Resource
    private DocumentCollectionService documentCollectionService;

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

    @Override
    public ResolvedResourceAccess resolve(Object identifier) {
        if (identifier == null) {
            throw new BusinessException("知识库不存在");
        }
        DocumentCollection collection = documentCollectionService.getDetail(String.valueOf(identifier));
        if (collection == null) {
            throw new BusinessException("知识库不存在");
        }
        return new ResolvedResourceAccess(collection, null);
    }
}
