package kr.co.accura.wbx.spring.datasource;

import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

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

/**
 * Multi-DataSource 설정 (선택적 활성화)
 * <p>
 * wbx.spring.datasource.routing-enabled=true 일 때 활성화.
 * 기본: 단일 DataSource (Spring Boot 자동 설정).
 * <p>
 * 사용법 (application.yml):
 * <pre>
 * wbx.spring.datasource.routing-enabled: true
 *
 * spring.datasource:           # 기본 (app)
 *   url: jdbc:mysql://...
 *
 * wbx.spring.datasource.wbxgw: # WBX Groupware DB (선택)
 *   url: jdbc:mysql://...
 *   username: xxx
 *   password: xxx
 *
 * wbx.spring.datasource.readonly: # 읽기전용 (선택)
 *   url: jdbc:mysql://...
 * </pre>
 */
@Slf4j
@Configuration
@ConditionalOnProperty(name = "wbx.spring.datasource.routing-enabled", havingValue = "true")
public class MultiDataSourceConfig {

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

    @Bean
    public DataSource appDataSource() {
        return appDataSourceProperties().initializeDataSourceBuilder()
                .type(HikariDataSource.class)
                .build();
    }

    @Bean
    @ConfigurationProperties("wbx.spring.datasource.wbxgw")
    public DataSourceProperties wbxgwDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    public DataSource wbxgwDataSource() {
        DataSourceProperties props = wbxgwDataSourceProperties();
        if (props.getUrl() == null || props.getUrl().isBlank()) {
            log.info("wbxgw datasource not configured, skipping");
            return appDataSource(); // fallback to app
        }
        return props.initializeDataSourceBuilder()
                .type(HikariDataSource.class)
                .build();
    }

    @Bean
    @Primary
    public DataSource routingDataSource(
            @Qualifier("appDataSource") DataSource appDs,
            @Qualifier("wbxgwDataSource") DataSource wbxgwDs) {

        WbxRoutingDataSource routing = new WbxRoutingDataSource();

        Map<Object, Object> targets = new HashMap<>();
        targets.put("app", appDs);
        targets.put("wbxgw", wbxgwDs);

        routing.setTargetDataSources(targets);
        routing.setDefaultTargetDataSource(appDs);
        routing.afterPropertiesSet();

        log.info("Multi-DataSource routing enabled: {}", targets.keySet());
        return routing;
    }
}
