package com.caliverse.admin.global.configuration;


import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
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.SimpleMongoClientDatabaseFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import com.caliverse.admin.logs.logrepository.mongobusinesslogrepository.MongoBusinessLogRepository;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;


@Configuration
@EnableMongoRepositories(basePackageClasses = MongoBusinessLogRepository.class, mongoTemplateRef = "mongoBusinessLogTemplate")
public class MongoBusinessLogConfig {
    
    @Value("${mongodb.host}")
    String businessLogHost;
    @Value("${mongodb.business-log.username}")
    String username;
    @Value("${mongodb.business-log.password}")
    String password;
    @Value("${mongodb.business-log.db}")
    String businessLogdb;
    

    @Bean(name = "mongoBusinessLogClient")
    public MongoClient mongoBusinessLogClient() {
        String encodePassword = URLEncoder.encode(password, StandardCharsets.UTF_8);
        String auth = username.isEmpty() ? "" : String.format("%s:%s@",username, encodePassword);
        String connection = String.format("mongodb://%s%s/?authSource=%s", auth, businessLogHost, businessLogdb);
        return MongoClients.create(connection);
    }

    @Bean(name = "mongoBusinessLogFactory")
    public MongoDatabaseFactory mongoBusinessLogFactory(@Qualifier("mongoBusinessLogClient") MongoClient mongoClient) {
        return new SimpleMongoClientDatabaseFactory(mongoClient, businessLogdb);
    }

    @Bean(name = "mongoBusinessLogTemplate")
    public MongoTemplate mongoBusinessLogTemplate(@Qualifier("mongoBusinessLogFactory") MongoDatabaseFactory mongoFactory) {
        return new MongoTemplate(mongoFactory);
    }

}
