package com.bcxin.backend.domain.configs;

import com.bcxin.backend.domain.baoans.models.DocumentDTO;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
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;

@Configuration
@EnableJpaRepositories(
        basePackages = "com.bcxin.backend.domain.baoans.repositories",
        entityManagerFactoryRef = "baoanEntityManagerFactory",
        transactionManagerRef = "baoanTransactionManager")
public class BaoanDomainConfig {

    @Bean("baoanDataSourceProperties")
    @ConfigurationProperties("spring.datasource.baoan")
    public DataSourceProperties baoanDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean("baoanDataSource")
    public DataSource baoanDataSource() {
        return baoanDataSourceProperties().initializeDataSourceBuilder().build();
    }

    @Bean(name = "baoanEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean baoanEntityManagerFactory(
            EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(baoanDataSource())
                .packages(DocumentDTO.class)
                //.packages("com.bcxin.backend.domain.baoans.models.models")
                .build();
    }

    @Bean("baoanTransactionManager")
    public PlatformTransactionManager baoanTransactionManager(
            final @Qualifier("baoanEntityManagerFactory")
                    LocalContainerEntityManagerFactoryBean baoanEntityManagerFactory) {
        return new JpaTransactionManager(baoanEntityManagerFactory.getObject());
    }
}