package com.caliverse.admin.global.configuration;


import com.caliverse.admin.Indicators.indicatorrepository.MongoIndicatorRepository;
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(basePackageClasses = MongoIndicatorRepository.class, mongoTemplateRef = "mongoIndicatorTemplate")
public class MongoIndicatorConfig {
    
//    @Value("${mongodb.indicator.uri}")
//    String uri;
    @Value("${mongodb.host}")
    String businessLogHost;
    @Value("${mongodb.indicator.username}")
    String username;
    @Value("${mongodb.indicator.password}")
    String password;
    @Value("${mongodb.indicator.db}")
    String db;

    @Bean(name = "mongoIndicatorClient")
    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 = "mongoIndicatorFactory")
    public MongoDatabaseFactory mongoIndicatorFactory(@Qualifier("mongoIndicatorClient") MongoClient mongoIndicatorClient) {
        return new SimpleMongoClientDatabaseFactory(mongoIndicatorClient, db);
    }

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

}
