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 DataSourceFourth {
    @Autowired
    private DataSourceConfig dataSourceConfig;

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

    @Bean
    @ConfigurationProperties("spring.datasource.fourth.configuration")
    public HikariDataSource fourthDataSource() {
        return fourthDataSourceProperties().initializeDataSourceBuilder()
                .type(HikariDataSource.class).build();
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean fourthEntityManagerFactory(
            EntityManagerFactoryBuilder builder, @Qualifier("fourthDataSource") 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.fourth")
                .persistenceUnit("fourth")
                .build();
    }

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

    @EnableJpaRepositories(basePackages = "cn.reghao.tnb.sb.multi.jpa.repository.fourth",
            entityManagerFactoryRef = "fourthEntityManagerFactory", transactionManagerRef = "fourthTransactionManager")
    public class FourthConfiguration {
    }
}
