package com.crm.rely.backend.configuration;

import com.crm.rely.backend.util.DynamicRoutingDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

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

/**
 * @Author houn
 * @Date 2024/12/24 13:59
 * @PackageName:com.crm.manager.configuration
 * @ClassName: DynamicDataSourceConfig
 * @Description: TODO
 */
@Slf4j
@Configuration
public class DataSourceConfig {

    @Value("${spring.dynamic-datasource.enable-auto-datasource-switch:false}")
    private boolean enableAutoDataSourceSwitch;

    @Lazy
    @Bean(name = "defaultDataSource")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource defaultDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "masterDataSource")
    @ConfigurationProperties(prefix = "spring.dynamic-datasource.datasource.master")
    public DataSource masterDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "slaveDataSource")
    @ConfigurationProperties(prefix = "spring.dynamic-datasource.datasource.slave")
    public DataSource slaveDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "dynamicDataSource")
    @Primary
    @DependsOn({"defaultDataSource", "masterDataSource", "slaveDataSource"})
    public DataSource dynamicDataSource(DataSource defaultDataSource,
                                        DataSource masterDataSource,
                                        DataSource slaveDataSource) {
        log.info("Loading dynamic data sources...");
        log.info("Default DataSource: {}", defaultDataSource);
        log.info("Master DataSource: {}", masterDataSource);
        log.info("Slave DataSource: {}", slaveDataSource);

        if (!enableAutoDataSourceSwitch) {
            return defaultDataSource; // 返回默认数据源
        }

        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put("master", masterDataSource);
        targetDataSources.put("slave", slaveDataSource);

        AbstractRoutingDataSource dynamicDataSource = new DynamicRoutingDataSource();
        dynamicDataSource.setDefaultTargetDataSource(masterDataSource);
        dynamicDataSource.setTargetDataSources(targetDataSources);

        return dynamicDataSource;
    }
}