package com.iqser.red.service.persistence.management.v1.processor.utils;

import java.util.HashMap;
import java.util.Map;

import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;

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

import lombok.SneakyThrows;

@Converter
public class JSONMapConverter implements AttributeConverter<Map<String, Object>, String> {

    private final ObjectMapper objectMapper = new ObjectMapper();


    @SneakyThrows
    @Override
    public String convertToDatabaseColumn(Map<String, Object> map) {

        return objectMapper.writeValueAsString(map);
    }


    @SneakyThrows
    @Override
    public Map<String, Object> convertToEntityAttribute(String data) {

        if (data == null) {
            return new HashMap<>();
        }
        TypeReference<HashMap<String, Object>> typeRef = new TypeReference<>() {
        };
        return objectMapper.readValue(data, typeRef);

    }

}
