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

import java.util.HashSet;
import java.util.Set;

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 JSONStringSetConverter implements AttributeConverter<Set<String>, String> {

    private final ObjectMapper objectMapper = new ObjectMapper();


    @SneakyThrows
    @Override
    public String convertToDatabaseColumn(Set<String> dataSet) {

        return objectMapper.writeValueAsString(dataSet);
    }


    @SneakyThrows
    @Override
    public Set<String> convertToEntityAttribute(String data) {

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

    }

}
