package com.microservices.mon.k8s.utils;

import com.alibaba.fastjson2.JSONObject;
import com.microservices.common.core.exception.ServiceException;
import com.microservices.common.core.utils.StringUtils;
import com.microservices.system.api.utils.FeignUtils;
import feign.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Slf4j
public class RancherResponseHandler {

    public static JSONObject handleJsonObject(Response response, String functionName, String errorMessage) {
        if (response != null) {
            Response.Body body = response.body();
            if (body != null) {
                try {
                    String bodyStr = IOUtils.toString(body.asInputStream(), StandardCharsets.UTF_8);
                    JSONObject bodyJson = JSONObject.parseObject(bodyStr);
                    if (FeignUtils.isSuccess(response)) {
                        return bodyJson;
                    }
                    if (bodyJson != null && bodyJson.containsKey("message")) {
                        log.error("{}时发生错误：{}", functionName, bodyJson.toJSONString());
                        if (StringUtils.isEmpty(errorMessage)) {
                            throw new ServiceException("%s时发生错误，错误原因：%s", functionName, bodyJson.getString("message"));
                        } else {
                            throw new ServiceException("%s时发生错误，错误原因：%s", functionName, errorMessage);
                        }

                    }
                } catch (IOException e) {
                    throw new ServiceException("%s时发生错误，响应数据读取异常", functionName);
                }
            }
        }

        throw new ServiceException("%s时发生错误，请联系系统管理员", functionName);
    }

    public static JSONObject handleJsonObject(Response response, String functionName) {
        return handleJsonObject(response, functionName, null);
    }


    public static Boolean handleBoolean(Response response, String functionName) {
        JSONObject bodyJson = handleJsonObject(response, functionName);
        return isSuccess(response, bodyJson);
    }


    public static Boolean handleBoolean(Response response, String functionName, String errorMessage) {
        JSONObject bodyJson = handleJsonObject(response, functionName, errorMessage);
        return isSuccess(response, bodyJson);
    }

    private static Boolean isSuccess(Response response, JSONObject bodyJson) {
        if (bodyJson != null) {
            return true;
        } else {
            return response.status() >= 200 && response.status() < 300;
        }
    }

}
