package com.caliverse.admin.global.configuration;


import com.caliverse.admin.history.repository.MongoAdminRepository;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
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 java.net.URLEncoder;
import java.nio.charset.StandardCharsets;


@Configuration
@EnableMongoRepositories(basePackages = "com.caliverse.admin.history.repository", mongoTemplateRef = "mongoAdminTemplate")
public class MongoAdminConfig {

    @Value("${mongodb.host}")
    String businessLogHost;
    @Value("${mongodb.admin.username}")
    String username;
    @Value("${mongodb.admin.password}")
    String password;
    @Value("${mongodb.admin.db}")
    String db;

    @Bean(name = "mongoAdminClient")
    public MongoClient mongoStatClient() {
        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, db);
        return MongoClients.create(connection);
    }

    @Bean(name = "mongoAdminFactory")
    public MongoDatabaseFactory mongoIndicatorFactory(@Qualifier("mongoAdminClient") MongoClient mongoIndicatorClient) {
        return new SimpleMongoClientDatabaseFactory(mongoIndicatorClient, db);
    }

    @Bean(name = "mongoAdminTemplate")
    public MongoTemplate mongoIndicatorTemplate(@Qualifier("mongoAdminFactory") MongoDatabaseFactory mongoIndicatorFactory) {
        return new MongoTemplate(mongoIndicatorFactory);
    }

}
