package com.bcxin.backend.domain.approval.configs;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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.approval.repositories.dest",
        entityManagerFactoryRef = "bjApprovalDestEntityManagerFactory",
        transactionManagerRef = "bjApprovalDestTransactionManager")
@ConditionalOnProperty(prefix = "myapps.bj-approval-data-push",name = "enable",havingValue = "true")
public class BjApprovalDataPushDestConfig {



    @Bean(name = "bjApprovalDestDataSource")
    @ConfigurationProperties("spring.datasource.bj-approval-dest")
    public DataSource bjApprovalDestDataSource() {
        return DataSourceBuilder.create().build();
    }



    @Bean("bjApprovalDestEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean bjApprovalDestEntityManagerFactory(
            EntityManagerFactoryBuilder builder,@Qualifier("bjApprovalDestDataSource") DataSource dataSource) {
        return builder.dataSource(dataSource).packages("com.bcxin.backend.domain.approval.entities.dest")
                .build();
    }

    @Bean("bjApprovalDestTransactionManager")
    public PlatformTransactionManager bjApprovalDestTransactionManager(
            final @Qualifier("bjApprovalDestEntityManagerFactory")
            LocalContainerEntityManagerFactoryBean entityManagerFactoryBean) {
        return new JpaTransactionManager(entityManagerFactoryBean.getObject());
    }
}
