package com.ecep.contract.ds;

import static com.ecep.contract.AppV2.DEFAULT_DB_DATABASE;
import static com.ecep.contract.AppV2.DEFAULT_DB_HOST;
import static com.ecep.contract.AppV2.DEFAULT_DB_PASSWORD;
import static com.ecep.contract.AppV2.DEFAULT_DB_PORT;
import static com.ecep.contract.AppV2.DEFAULT_DB_USERNAME;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.repository.config.BootstrapMode;
import org.springframework.jdbc.core.JdbcTemplate;

import com.zaxxer.hikari.HikariDataSource;

@Configuration
@EnableJpaRepositories(
    basePackages = {"com.ecep.contract.ds"}, 
    bootstrapMode = BootstrapMode.LAZY,
    repositoryFactoryBeanClass = JpaRepositoryFactoryBean.class
)
public class DsRepositoriesConfig {
    private static final Logger logger = LoggerFactory.getLogger(DsRepositoriesConfig.class);

    @Bean
    // @ConfigurationProperties(prefix = "spring.datasource")
    @Primary
    public DataSource dataSource(Environment env) {
        if (logger.isDebugEnabled()) {
            logger.debug("SpringApp.dataSource, env:{}", env);
        }

        String host = env.getProperty("db.server.host", DEFAULT_DB_HOST);
        String port = env.getProperty("db.server.port", DEFAULT_DB_PORT);
        String database = env.getProperty("db.server.database", DEFAULT_DB_DATABASE);
        String username = env.getProperty("db.server.username", DEFAULT_DB_USERNAME);
        String password = env.getProperty("db.server.password", DEFAULT_DB_PASSWORD);

        String url = "jdbc:mysql://" + host + ":" + port + "/" + database;
        if (logger.isDebugEnabled()) {
            logger.debug("db server url:{},user:{}", url, username);
        }

        return DataSourceBuilder.create()
                .type(HikariDataSource.class)
                .url(url)
                .username(username)
                .password(password)
                .driverClassName("com.mysql.cj.jdbc.Driver")
                .build();
    }

    @Primary
    @Bean
    public JdbcTemplate jdbcTemplate(@Qualifier("dataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}
