package cn.novalon.manage.app.config;

import io.r2dbc.spi.ConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.r2dbc.connection.init.ConnectionFactoryInitializer;
import org.springframework.r2dbc.connection.init.ResourceDatabasePopulator;

/**
 * R2DBC数据库初始化配置
 * 
 * 用于测试环境的H2数据库初始化
 * 
 * @author 张翔
 * @date 2026-04-03
 */
@Configuration
@ConditionalOnProperty(name = "spring.profiles.active", havingValue = "test")
public class R2dbcInitConfig {

    private static final Logger logger = LoggerFactory.getLogger(R2dbcInitConfig.class);

    @Bean
    public ConnectionFactoryInitializer connectionFactoryInitializer(ConnectionFactory connectionFactory) {
        logger.info("Initializing R2DBC database with H2 schema and data");
        
        ConnectionFactoryInitializer initializer = new ConnectionFactoryInitializer();
        initializer.setConnectionFactory(connectionFactory);
        
        ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
        populator.addScript(new ClassPathResource("schema-h2.sql"));
        populator.addScript(new ClassPathResource("data-h2.sql"));
        
        initializer.setDatabasePopulator(populator);
        
        return initializer;
    }
}
