package ru.kirillius.pf.sdn.entity;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import ru.kirillius.pf.sdn.api.Networking.NetworkScope;

@Converter
public class NetworkScopeConverter implements AttributeConverter<NetworkScope, String> {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Override
    public String convertToDatabaseColumn(NetworkScope attribute) {
        if (attribute == null) return null;
        try {
            return MAPPER.writeValueAsString(attribute);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Failed to serialize NetworkScope", e);
        }
    }

    @Override
    public NetworkScope convertToEntityAttribute(String dbData) {
        if (dbData == null) return null;
        try {
            return MAPPER.readValue(dbData, NetworkScope.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Failed to deserialize NetworkScope", e);
        }
    }
}
