package com.usky.issue.service.util;

import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.util.StringUtils;

/**
 * ApiResult 响应解析
 *
 * @author fyc
 * @date 2026-06-29
 */
public final class ApiResultParser {

    private ApiResultParser() {
    }

    /** 本项目 ApiResult 成功：status=SUCCESS 或 code=0/"0"/200 */
    public static boolean isSuccess(JsonNode json) {
        if (json == null || json.isNull()) {
            return false;
        }
        if (json.has("status")) {
            String status = json.get("status").asText("");
            if ("SUCCESS".equalsIgnoreCase(status)) {
                return true;
            }
            if ("FAIL".equalsIgnoreCase(status) || "ERROR".equalsIgnoreCase(status)) {
                return false;
            }
        }
        if (json.has("code")) {
            JsonNode codeNode = json.get("code");
            if (codeNode.isTextual()) {
                String code = codeNode.asText();
                return "0".equals(code) || "200".equals(code);
            }
            if (codeNode.isNumber()) {
                int code = codeNode.asInt();
                return code == 0 || code == 200;
            }
        }
        return true;
    }

    public static String resolveMessage(JsonNode json) {
        if (json == null) {
            return null;
        }
        String msg = json.path("msg").asText(null);
        if (StringUtils.hasText(msg)) {
            return msg;
        }
        msg = json.path("message").asText(null);
        if (StringUtils.hasText(msg)) {
            return msg;
        }
        return json.path("errorSummary").asText(null);
    }
}
