package org.raddatz.familienarchiv.document.annotation;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;

import java.util.List;

@Converter
public class PolygonConverter implements AttributeConverter<List<List<Double>>, String> {

    private static final ObjectMapper MAPPER = new ObjectMapper();
    private static final TypeReference<List<List<Double>>> TYPE_REF = new TypeReference<>() {};

    @Override
    public String convertToDatabaseColumn(List<List<Double>> polygon) {
        if (polygon == null) return null;
        try {
            return MAPPER.writeValueAsString(polygon);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("Failed to serialize polygon", e);
        }
    }

    @Override
    public List<List<Double>> convertToEntityAttribute(String json) {
        if (json == null || json.isEmpty()) return null;
        try {
            return MAPPER.readValue(json, TYPE_REF);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("Failed to deserialize polygon", e);
        }
    }
}
