package tech.easyflow.ai.permission;

import org.springframework.stereotype.Component;
import tech.easyflow.ai.entity.Workflow;
import tech.easyflow.ai.entity.WorkflowExecResult;
import tech.easyflow.ai.service.WorkflowExecResultService;
import tech.easyflow.ai.service.WorkflowService;
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 WorkflowExecKeyResourceAccessResolver implements ResourceAccessResolver {

    @Resource
    private WorkflowExecResultService workflowExecResultService;

    @Resource
    private WorkflowService workflowService;

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

    @Override
    public ResolvedResourceAccess resolve(Object identifier) {
        if (identifier == null) {
            throw new BusinessException("工作流执行记录不存在");
        }
        WorkflowExecResult execResult = workflowExecResultService.getByExecKey(String.valueOf(identifier));
        if (execResult == null) {
            throw new BusinessException("工作流执行记录不存在");
        }
        Workflow workflow = workflowService.getDetail(String.valueOf(execResult.getWorkflowId()));
        if (workflow == null) {
            throw new BusinessException("工作流不存在");
        }
        return new ResolvedResourceAccess(workflow, execResult.getCreatedBy());
    }
}
