package com.cool.store.utils;

import com.cool.store.response.PaymentDetail;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


public  class CustomMapDeserializer extends JsonDeserializer<Map<String, PaymentDetail>> {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public Map<String, PaymentDetail> deserialize(JsonParser p, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        JsonNode node = p.getCodec().readTree(p);

        // 如果是数组，则返回空 Map
        if (node.isArray()) {
            return new HashMap<>();
        }

        // 如果是对象，则解析为 Map<String, PaymentDetail>
        Map<String, PaymentDetail> map = new HashMap<>();
        node.fields().forEachRemaining(entry -> {
            try {
                PaymentDetail paymentDetail = objectMapper.treeToValue(entry.getValue(), PaymentDetail.class);
                map.put(entry.getKey(), paymentDetail);
            } catch (Exception e) {
                throw new RuntimeException("Failed to deserialize PaymentDetail", e);
            }
        });
        return map;
    }
}