package com.bonus.mongodb.config;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.URLEncoder;


/**
 * @author coisini
 * @version 1.0
 * @Description MongoDB配置类
 * @date Apr 17, 2022
 */
@Configuration
@ConfigurationProperties(prefix = "spring.data.mongodb")
@Data
public class MongoConfig {
    /**
     * 数据库配置信息
     */
    private String database;
    private String host;
    private Integer port;
    private String username;
    private String password;

    // 移除静态修饰符，避免单例模式
    private MongoClient mongoClient;

    // 使用@Bean注解，并在方法内部进行异常处理
    @Bean
    public MongoClient getMongoClient() {
        if (mongoClient == null) {
            try {
                mongoClient = MongoClients.create(String.format("mongodb://%s:%s@%s:%d/%s", URLEncoder.encode(username, "UTF-8"),URLEncoder.encode(password, "UTF-8"), host, port, database));
            } catch (Exception e) {
                // 在实际应用中应该有更详细的异常处理策略，例如记录日志并抛出自定义异常
                throw new RuntimeException("Failed to create MongoClient", e);
            }
        }
        return mongoClient;
    }

    // 直接返回MongoDatabase实例，依赖注入会处理实例的获取
    public MongoDatabase getMongoDatabase() {
        return getMongoClient().getDatabase(database);
    }

    // 创建GridFSBucket的@Bean方法，依赖注入MongoDatabase
    @Bean
    public GridFSBucket getGridFsBucket() {
        return GridFSBuckets.create(getMongoDatabase());
    }
}
