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

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
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("HTTP")
@RequiredArgsConstructor
public class FlowHttpNodeHandler implements FlowNodeTypeHandler {

    @Override
    public TaskNodeExecuteResult handle(TaskNodeExecuteMessage message) {
        try {
            JSONObject inputParams = message.getInputParams();
            JSONObject config = inputParams.getJSONObject("config");
            JSONObject body = inputParams.getJSONObject("body");
            JSONObject headers = inputParams.getJSONObject("headers");
            // 1. 必填参数校验
            String url = config.getString("url");
            if (url == null || url.isEmpty()) {
                return TaskNodeExecuteResult.failure("HTTP url is required");
            }

            String method = config.getString("method");
            if (method == null) {
                method = "POST";
            }

            int timeout = config.getIntValue("timeout", 100000);


            Object bodyCfg = null;
            if (!"json".equals(body.getString("bodyType"))) {
                JSONObject formData = body.getJSONObject("formData");
                bodyCfg = formData;
            } else {
                bodyCfg = body.get("json");
            }
            // 2. 构造 HTTP 请求
            HttpRequest request = HttpRequest.of(url)
                    .method(Method.valueOf(method.toUpperCase()))
                    .timeout(timeout);

            // 3. headers（可选）
            if (headers != null) {
                for (String key : headers.keySet()) {
                    String value = headers.getString(key);
                    if (value != null) {
                        request.header(key, value);
                    }
                }
            }

            // 4. body（可选，JSON）
            if (bodyCfg != null) {
                request.header("Content-Type", "application/json");
                request.body(bodyCfg.toString());
            }

            log.info("[FLOW][HTTP] {} {}", method, url);

            // 5. 执行请求
            HttpResponse response = request.execute();

            if (!response.isOk()) {
                log.error("[FLOW][HTTP] 调用失败，status={}", response.getStatus());
                return TaskNodeExecuteResult.failure("HTTP status=" + response.getStatus());
            }

            // 6. 原样解析返回（JSON / String）
            Object resp;
            String respBody = response.body();
            try {
                resp = JSON.parse(respBody);
            } catch (Exception e) {
                resp = respBody;
            }

            JSONObject output = new JSONObject();
            output.put("result", resp);

            log.info(
                    "[FLOW][HTTP] success, nodeId={}, responseType={}",
                    message.getNodeId(),
                    resp.getClass().getSimpleName()
            );

            return TaskNodeExecuteResult.success(output);

        } catch (Exception e) {
            log.error("[FLOW][HTTP] 执行异常", e);
            return TaskNodeExecuteResult.failure(e.getMessage());
        }
    }
}
