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

import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component("SLEEP")
@RequiredArgsConstructor
public class FlowSleepNodeHandler implements FlowNodeTypeHandler {

    @Override
    public TaskNodeExecuteResult handle(TaskNodeExecuteMessage message) {
        String nodeId = message.getNodeId();
        long delayMs = getDelayFromNodeParams(message);

        if (delayMs <= 0) {
            log.warn("SLEEP 节点 {} 未配置有效延迟，直接跳过", nodeId);
            return TaskNodeExecuteResult.success(message.getInputParams());
        }

        log.info("SLEEP 节点 {} 开始等待 {} ms", nodeId, delayMs);

        try {
            Thread.sleep(delayMs);
        } catch (InterruptedException e) {
            // 暂停或终止时会 interrupt()
            log.info("SLEEP 节点 {} 在睡眠中被中断", nodeId);
            Thread.currentThread().interrupt(); // 还原中断标志
            return null; // 或抛异常交给 FlowExceptionInterceptor 走中断流程
        }

        log.info("SLEEP 节点 {} 完成等待", nodeId);
        return TaskNodeExecuteResult.success(message.getInputParams());
    }

    private long getDelayFromNodeParams(TaskNodeExecuteMessage message) {
        String val = message.getInputParams().getString("delayMs");
        if (val != null) {
            try {
                return Long.parseLong(val);
            } catch (NumberFormatException ignored) {
            }
        }
        return 0;
    }
}
