package com.banesco.commons.helper;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import io.quarkus.runtime.util.StringUtil;
import jakarta.enterprise.context.ApplicationScoped;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ApplicationScoped
public class JsonHelper {
    public static final ObjectMapper MAPPER = new ObjectMapper();

    public JsonHelper() {
        MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }


    public String getJsonFromObject(Object object) {
        try {
            return MAPPER.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.error("Object To Json Exception: {}", e.getMessage());
        }
        return null;
    }


    public <T> T getObjectFromJson(String json, Class<T> className) {
        if (!StringUtil.isNullOrEmpty(json)) {
            try {
                return MAPPER.readValue(json, className);
            } catch (JsonProcessingException | IllegalArgumentException e) {
                log.error("JSON to Object Exception: {}", e.getMessage());
            }
        }
        return null;
    }
}
