package com.cmvr.test.flow.runtime.interceptor;

import com.cmvr.test.flow.runtime.event.FlowExecutionEvent;
import com.cmvr.test.flow.runtime.event.FlowExecutionEventPublisher;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.function.Function;

@Slf4j
@Component
@Order(6)
public class FlowAfterInterceptor extends AbstractFlowMsgPreInterceptor{

    public FlowAfterInterceptor(FlowExecutionEventPublisher eventPublisher) {
        super(eventPublisher);
    }

    @Override
    public TaskNodeExecuteResult doIntercept(TaskNodeExecuteMessage message, Function<TaskNodeExecuteMessage, TaskNodeExecuteResult> next) {
        TaskNodeExecuteResult result = next.apply(message);
        FlowExecutionEvent.EventType eventType;
        String errorMessage = null;

        if (result != null && result.isSuccess()) {
            eventType = FlowExecutionEvent.EventType.NODE_COMPLETED;
        } else {
            eventType = FlowExecutionEvent.EventType.NODE_FAILED;
            errorMessage = result != null ? result.getErrorMsg() : "执行结果为空";
        }

        FlowExecutionEvent event = FlowExecutionEvent.builder()
                .eventType(eventType)
                .nodeName(message.getNodeName())
                .instId(message.getInstId())
                .nodeName(message.getNodeName())
                .taskId(message.getTaskId())
                .itemId(message.getItemId())
                .nodeId(message.getNodeId())
                .nodeCount(message.getGraph().allNodeIds().size())
                .nodeType(message.getNodeType())
                .errorMessage(errorMessage)
                .build();

        eventPublisher.publishEvent(event);
        return result;
    }
}
