package de.oaa.xxx.games.chastity.cardlock;

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

import java.util.ArrayList;
import java.util.List;

@Converter
public class CardEnumListConverter implements AttributeConverter<List<CardEnum>, String> {

    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    public String convertToDatabaseColumn(List<CardEnum> list) {
        if (list == null || list.isEmpty()) return null;
        try {
            return mapper.writeValueAsString(list.stream().map(Enum::name).toList());
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public List<CardEnum> convertToEntityAttribute(String json) {
        if (json == null || json.isBlank()) return new ArrayList<>();
        try {
            List<String> names = mapper.readValue(json, new TypeReference<>() {});
            return new ArrayList<>(names.stream().map(CardEnum::valueOf).toList());
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }
}
