package tech.easyflow.ai.easyagentsflow.upload;

import com.easyagents.flow.core.chain.Chain;
import com.easyagents.flow.core.chain.Event;
import com.easyagents.flow.core.chain.event.ChainStatusChangeEvent;
import com.easyagents.flow.core.chain.listener.ChainEventListener;
import org.springframework.stereotype.Component;

/**
 * 工作流终态事件到临时上传清理队列的桥接监听器。
 */
@Component
public class WorkflowApiUploadCleanupListener implements ChainEventListener {

    private final WorkflowApiUploadLifecycleService lifecycleService;

    /**
     * 创建临时上传清理监听器。
     *
     * @param lifecycleService 临时上传生命周期服务
     */
    public WorkflowApiUploadCleanupListener(
            WorkflowApiUploadLifecycleService lifecycleService) {
        this.lifecycleService = lifecycleService;
    }

    /**
     * 在工作流进入终态后触发异步清理登记。
     *
     * @param event 工作流事件
     * @param chain 工作流实例
     */
    @Override
    public void onEvent(Event event, Chain chain) {
        if (event instanceof ChainStatusChangeEvent statusChangeEvent
                && statusChangeEvent.getStatus() != null
                && statusChangeEvent.getStatus().isTerminal()) {
            lifecycleService.markExecutionTerminal(
                    chain.getStateInstanceId());
        }
    }
}
