package tech.easyflow.ai.permission;

import org.springframework.stereotype.Component;
import tech.easyflow.ai.entity.DocumentCollection;
import tech.easyflow.ai.entity.FaqCategory;
import tech.easyflow.ai.service.DocumentCollectionService;
import tech.easyflow.ai.service.FaqCategoryService;
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 FaqCategoryIdKnowledgeResourceAccessResolver implements ResourceAccessResolver {

    @Resource
    private FaqCategoryService faqCategoryService;

    @Resource
    private DocumentCollectionService documentCollectionService;

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

    @Override
    public ResolvedResourceAccess resolve(Object identifier) {
        if (identifier == null) {
            throw new BusinessException("FAQ分类不存在");
        }
        FaqCategory faqCategory = faqCategoryService.getById(String.valueOf(identifier));
        if (faqCategory == null) {
            throw new BusinessException("FAQ分类不存在");
        }
        DocumentCollection collection = documentCollectionService.getById(faqCategory.getCollectionId());
        if (collection == null) {
            throw new BusinessException("知识库不存在");
        }
        return new ResolvedResourceAccess(collection, null);
    }
}
