package com.bcxin.backend.domain.system.configs;
import com.bcxin.backend.domain.system.entities.UserDTO;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

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

@Configuration
@EnableJpaRepositories(
        basePackages = "com.bcxin.backend.domain.system.repositories",
        entityManagerFactoryRef = "entityManagerFactory_system",
        transactionManagerRef = "transactionManager_system")
@EnableConfigurationProperties({
        DispatchProperties.class,
        DispatchSiteResourceProperties.class
})
public class SysConfig {
    public SysConfig() {

    }
    @Bean("entityManagerFactory_system")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(
            @Qualifier("dataSource") DataSource dataSource,
            EntityManagerFactoryBuilder builder) {
        Map<String, String> properties = new HashMap<>();
        properties.put("hibernate.hbm2ddl.auto", "none");
        properties.put("hibernate.show_sql", "true");

        return builder.dataSource(dataSource)
                .properties(properties)
                .packages(UserDTO.class)
                .build();
    }

    @Bean("transactionManager_system")
    public PlatformTransactionManager transactionManager(
            final @Qualifier("entityManagerFactory_system")
                    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean) {
        return new JpaTransactionManager(entityManagerFactoryBean.getObject());
    }
}
