package com.magistr.app.config;

import com.magistr.app.config.tenant.TenantConfig;
import com.magistr.app.config.tenant.TenantConfigWatcher;
import com.magistr.app.config.tenant.TenantRoutingDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * При запуске приложения инициализирует БД для каждого тенанта.
 * Делегирует инициализацию в TenantConfigWatcher.initDatabaseForTenant().
 */
@Component
public class DataInitializer implements CommandLineRunner {

    private static final Logger log = LoggerFactory.getLogger(DataInitializer.class);

    private final TenantRoutingDataSource routingDataSource;
    private final TenantConfigWatcher configWatcher;

    public DataInitializer(TenantRoutingDataSource routingDataSource,
                           TenantConfigWatcher configWatcher) {
        this.routingDataSource = routingDataSource;
        this.configWatcher = configWatcher;
    }

    @Override
    public void run(String... args) {
        log.info("Initializing databases for {} tenant(s)...", routingDataSource.getTenantConfigs().size());

        for (TenantConfig tenant : routingDataSource.getTenantConfigs().values()) {
            configWatcher.initDatabaseForTenant(tenant);
        }

        log.info("Database initialization complete");
    }
}
