package com.ai.trackwalker.common;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;
import java.util.Map;

public final class Jsonb {
    public static final ObjectMapper MAPPER = new ObjectMapper();

    private Jsonb() {
    }

    public static String write(Object value) {
        try {
            return MAPPER.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("Invalid JSON value", e);
        }
    }

    public static Map<String, Object> map(String value) {
        try {
            return MAPPER.readValue(value == null ? "{}" : value, new TypeReference<>() {
            });
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("Invalid JSON map", e);
        }
    }

    public static List<String> stringList(String value) {
        try {
            return MAPPER.readValue(value == null ? "[]" : value, new TypeReference<>() {
            });
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("Invalid JSON list", e);
        }
    }

    public static List<Map<String, Object>> mapList(String value) {
        try {
            return MAPPER.readValue(value == null ? "[]" : value, new TypeReference<>() {
            });
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("Invalid JSON list", e);
        }
    }

    public static Object read(String value) {
        try {
            return MAPPER.readValue(value == null ? "null" : value, Object.class);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("Invalid JSON value", e);
        }
    }
}
