package com.zhentao.config;

import com.mongodb.client.MongoClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

/**
 * MongoDB配置类
 * 用于三重存储架构的NoSQL部分
 */
@Configuration
@EnableMongoRepositories(basePackages = "com.zhentao.repository")
public class MongoDBConfig {
    
    /**
     * 配置MongoTemplate
     * 移除_class字段（MongoDB默认会添加这个字段）
     */
    @Bean
    public MongoTemplate mongoTemplate(MongoDatabaseFactory mongoDbFactory, 
                                       MongoMappingContext context) {
        MappingMongoConverter converter = new MappingMongoConverter(
            new DefaultDbRefResolver(mongoDbFactory), context);
        
        // 移除_class字段
        converter.setTypeMapper(new DefaultMongoTypeMapper(null));
        
        return new MongoTemplate(mongoDbFactory, converter);
    }
    
    /**
     * MongoDB连接测试
     */
    @Bean
    public String mongoConnectionTest(MongoTemplate mongoTemplate) {
        try {
            // 测试连接
            mongoTemplate.getDb().getName();
            System.out.println("✅ MongoDB连接成功！数据库: " + mongoTemplate.getDb().getName());
            return "MongoDB连接成功";
        } catch (Exception e) {
            System.err.println("❌ MongoDB连接失败: " + e.getMessage());
            return "MongoDB连接失败";
        }
    }
}

