package com.dbnt.kcscopensearch.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;

@Configuration
@EnableJpaRepositories(
    basePackages = "com.dbnt.kcscopensearch.kcsc.**.repository",
    entityManagerFactoryRef = "kcscEntityManager",
    transactionManagerRef = "kcscTransactionManager"
)
@ComponentScan(basePackageClasses = KcscDatabaseConfig.class)
public class KcscDatabaseConfig {

  @Bean
  public LocalContainerEntityManagerFactoryBean kcscEntityManager(){
    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(kcscDataSource());

    //Entity 패키지 경로
    em.setPackagesToScan(new String[] { "com.dbnt.kcscopensearch.kcsc.**.model" });

    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);

    //Hibernate 설정
    HashMap<String, Object> properties = new HashMap<>();
    properties.put("hibernate.hbm2ddl.auto", "none");
    properties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
    em.setJpaPropertyMap(properties);
    return em;
  }

  @Primary
  @Bean
  @ConfigurationProperties(prefix="spring.datasource-kcsc")
  public DataSource kcscDataSource() {
    return DataSourceBuilder.create().build();
  }

  @Primary
  @Bean
  public PlatformTransactionManager kcscTransactionManager() {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(kcscEntityManager().getObject());
    return transactionManager;
  }

}
