package com.gxwebsoft.common.core.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * Jackson配置检查器
 * 在应用启动时检查Jackson配置是否正确
 *
 * @author WebSoft
 * @since 2025-09-08
 */
@Component
public class JacksonConfigChecker implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(JacksonConfigChecker.class);

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void run(String... args) throws Exception {
        logger.info("=== Jackson配置检查开始 ===");
        
        try {
            // 检查JavaTimeModule是否注册
            boolean hasJavaTimeModule = objectMapper.getRegisteredModuleIds()
                    .contains(JavaTimeModule.class.getName());
            logger.info("JavaTimeModule是否注册: {}", hasJavaTimeModule);
            
            // 测试LocalDateTime序列化
            Map<String, Object> testData = new HashMap<>();
            testData.put("currentTime", LocalDateTime.now());
            testData.put("message", "Jackson配置测试");
            
            String json = objectMapper.writeValueAsString(testData);
            logger.info("LocalDateTime序列化测试成功: {}", json);
            
            // 测试反序列化
            Map<String, Object> result = objectMapper.readValue(json, Map.class);
            logger.info("反序列化测试成功: {}", result);
            
            logger.info("=== Jackson配置检查完成 - 配置正常 ===");
            
        } catch (Exception e) {
            logger.error("=== Jackson配置检查失败 ===", e);
            logger.error("请检查Jackson配置是否正确");
        }
    }
}
