package com.erp.tenant;

import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * 기본 DataSource 를 {@link TenantRoutingDataSource} 로 교체.
 * - @Bean DataSource 를 제공하므로 Spring Boot DataSourceAutoConfiguration 의 자동 DataSource 는 스킵됨.
 * - MyBatis / TransactionManager 등 하위 컴포넌트는 이 @Primary bean 을 자동으로 사용.
 */
@Configuration
@Slf4j
public class DataSourceConfig {

    @Bean
    public TenantDbSettings tenantDbSettings(DataSourceProperties props) {
        TenantDbSettings s = TenantDbSettings.fromJdbcUrl(props.getUrl(), props.getUsername(), props.getPassword());
        log.info("[DataSourceConfig] tenant default endpoint: {}:{}", s.host(), s.port());
        return s;
    }

    @Bean
    @Primary
    public TenantRoutingDataSource dataSource(DataSourceProperties props) {
        HikariDataSource meta = TenantDataSourceFactory.createMeta(
                props.getUrl(), props.getUsername(), props.getPassword());
        TenantRoutingDataSource routing = new TenantRoutingDataSource();
        routing.registerMeta(meta);
        return routing;
    }
}
