package com.ruoyi.lsfx.domain.response;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.DeserializationContext;

import java.io.IOException;

public class CreditParsePayloadDeserializer extends JsonDeserializer<CreditParsePayload> {

    @Override
    public CreditParsePayload deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        ObjectCodec codec = parser.getCodec();
        JsonNode node = codec.readTree(parser);
        if (node == null || node.isNull()) {
            return null;
        }
        if (node.isTextual()) {
            String payloadText = node.asText();
            if (payloadText == null || payloadText.trim().isEmpty()) {
                return null;
            }
            node = codec.readTree(codec.getFactory().createParser(payloadText));
        }
        if (!node.isObject()) {
            throw JsonMappingException.from(parser, "征信解析payload格式不支持");
        }
        return codec.treeToValue(node, CreditParsePayload.class);
    }
}
