package com.qqchen.deploy.backend.framework.converter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qqchen.deploy.backend.framework.dto.DiskInfo;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import lombok.extern.slf4j.Slf4j;

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

/**
 * 磁盘信息列表 JSON 转换器
 */
@Slf4j
@Converter
public class DiskInfoListConverter implements AttributeConverter<List<DiskInfo>, String> {
    
    private static final ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    public String convertToDatabaseColumn(List<DiskInfo> attribute) {
        if (attribute == null || attribute.isEmpty()) {
            return null;
        }
        try {
            return objectMapper.writeValueAsString(attribute);
        } catch (JsonProcessingException e) {
            log.error("转换磁盘信息为JSON失败", e);
            return null;
        }
    }
    
    @Override
    public List<DiskInfo> convertToEntityAttribute(String dbData) {
        if (dbData == null || dbData.trim().isEmpty()) {
            return new ArrayList<>();
        }
        try {
            return objectMapper.readValue(dbData, new TypeReference<List<DiskInfo>>() {});
        } catch (JsonProcessingException e) {
            log.error("解析磁盘信息JSON失败: {}", dbData, e);
            return new ArrayList<>();
        }
    }
}
