package com.aps.service.codeGeneratorService;


import com.aps.entity.codeGeneratorEntity.DatabaseConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@EnableConfigurationProperties
public class DatabaseConfigService {

    @Autowired
    private Environment environment;

    /**
     * 获取当前主数据源配置
     */
    public DatabaseConfig getPrimaryDatabaseConfig() {
        // 获取主数据源名称
        String primaryDataSource = environment.getProperty("spring.datasource.dynamic.primary", "sqlserver");
        return getDatabaseConfig(primaryDataSource);
    }

    /**
     * 获取指定数据源配置
     */
    public DatabaseConfig getDatabaseConfig(String dataSourceName) {
        DatabaseConfig config = new DatabaseConfig();
        
        // 从配置文件中读取数据源信息
        String url = environment.getProperty("spring.datasource.dynamic.datasource." + dataSourceName + ".url");
        String username = environment.getProperty("spring.datasource.dynamic.datasource." + dataSourceName + ".username");
        String password = environment.getProperty("spring.datasource.dynamic.datasource." + dataSourceName + ".password");
        String driverClassName = environment.getProperty("spring.datasource.dynamic.datasource." + dataSourceName + ".driver-class-name");
        
        if (url != null) {
            config.setUrl(url);
            config.setUsername(username);
            config.setPassword(password);
            config.setDriverClassName(driverClassName);
            config.setDbType(dataSourceName);
            return config;
        }
        
        return null;
    }

    /**
     * 获取所有数据源配置
     */
    public Map<String, DatabaseConfig> getAllDatabaseConfigs() {
        Map<String, DatabaseConfig> configs = new HashMap<>();
        
        String[] dataSources = {"mysql", "oracle", "sqlserver"};
        for (String dataSource : dataSources) {
            DatabaseConfig config = getDatabaseConfig(dataSource);
            if (config != null && config.getUrl() != null) {
                configs.put(dataSource, config);
            }
        }
        
        return configs;
    }

    /**
     * 测试数据库连接
     */
    public boolean testConnection(DatabaseConfig config) {
        if (config == null || config.getUrl() == null) {
            return false;
        }
        
        try {
            Class.forName(config.getDriverClassName());
            try (java.sql.Connection connection = java.sql.DriverManager.getConnection(
                    config.getUrl(), config.getUsername(), config.getPassword())) {
                return connection.isValid(5);
            }
        } catch (Exception e) {
            return false;
        }
    }
}