package com.aps.common.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

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

/**
 * 最常用的深拷贝工具类
 */
public class DeepCopyUtil {
    
    private static final ObjectMapper objectMapper = new ObjectMapper();
    
    /**
     * 单个对象深拷贝（最常用）
     */
    @SuppressWarnings("unchecked")
    public static <T> T deepCopy(T source) {
        if (source == null) return null;
        
        try {
            String json = objectMapper.writeValueAsString(source);
            return (T) objectMapper.readValue(json, source.getClass());
        } catch (Exception e) {
            throw new RuntimeException("深拷贝失败", e);
        }
    }
    
    /**
     * 列表深拷贝（很常用）
     */
    public static <T> List<T> deepCopyList(List<T> source) {
        if (source == null) {
            return new ArrayList<>();  // 替换 List.of()

        }
        
        try {
            String json = objectMapper.writeValueAsString(source);
            return objectMapper.readValue(json, new TypeReference<List<T>>() {});
        } catch (Exception e) {
            throw new RuntimeException("列表深拷贝失败", e);
        }
    }
    
    /**
     * 安全深拷贝（返回Optional，避免异常）
     */
    public static <T> Optional<T> safeDeepCopy(T source) {
        try {
            return Optional.ofNullable(deepCopy(source));
        } catch (Exception e) {
            return Optional.empty();
        }
    }
}