package cn.reghao.tnb.sb.multi.jpa.ds;

import cn.reghao.tnb.sb.multi.jpa.DataSourceConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
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;
import java.util.Map;

/**
 * @author reghao
 * @date 2024-12-17 10:19:39
 */
@Configuration
public class DataSourceThird {
    @Autowired
    private DataSourceConfig dataSourceConfig;

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

    @Bean
    @ConfigurationProperties("spring.datasource.third.configuration")
    public HikariDataSource thirdDataSource() {
        return thirdDataSourceProperties().initializeDataSourceBuilder()
                .type(HikariDataSource.class).build();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean thirdEntityManagerFactory(
            EntityManagerFactoryBuilder builder, @Qualifier("thirdDataSource") DataSource dataSource) {
        Map<String, Object> map = dataSourceConfig.getVendorProperties(dataSource);
        return builder
                .dataSource(dataSource)
                // 加入规约配置
                .properties(dataSourceConfig.getVendorProperties(dataSource))
                .packages("cn.reghao.tnb.sb.multi.jpa.entity.third")
                .persistenceUnit("third")
                .build();
    }

    @Bean
    public PlatformTransactionManager thirdTransactionManager(
            @Qualifier("thirdEntityManagerFactory") LocalContainerEntityManagerFactoryBean entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory.getObject());
    }

    @EnableJpaRepositories(basePackages = "cn.reghao.tnb.sb.multi.jpa.repository.third",
            entityManagerFactoryRef = "thirdEntityManagerFactory", transactionManagerRef = "thirdTransactionManager")
    public class ThirdConfiguration {
    }
}
