package com.bizzan.bitrade.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Market MySQL 第二数据源配置
 *
 * 设计要点：
 * 1. DataSource 不暴露为 Spring Bean，仅在方法内部创建，
 *    避免触发 Spring Boot JPA 自动配置的 @ConditionalOnMissingBean(DataSource.class) back-off。
 * 2. 只注册 SqlSessionFactory Bean，供 @MapperScan 创建 FuturesKlineMapper 代理 Bean。
 * 3. 开启 mapUnderscoreToCamelCase，自动映射 begin_time → beginTime。
 */
@Configuration
@MapperScan(
        basePackages = "com.bizzan.bitrade.mapper.market",
        sqlSessionFactoryRef = "marketSqlSessionFactory"
)
public class MarketDataSourceConfig {

    @Value("${spring.datasource.market.url}")
    private String url;

    @Value("${spring.datasource.market.username}")
    private String username;

    @Value("${spring.datasource.market.password}")
    private String password;

    @Bean(name = "marketSqlSessionFactory")
    public SqlSessionFactory marketSqlSessionFactory() throws Exception {
        DruidDataSource ds = new DruidDataSource();
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setInitialSize(2);
        ds.setMinIdle(2);
        ds.setMaxActive(20);

        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        factoryBean.setDataSource(ds);

        com.baomidou.mybatisplus.core.MybatisConfiguration configuration = new com.baomidou.mybatisplus.core.MybatisConfiguration();
        configuration.setMapUnderscoreToCamelCase(true);
        factoryBean.setConfiguration(configuration);

        return factoryBean.getObject();
    }
}
