package com.aps.service.codeGeneratorService;


import com.aps.entity.codeGeneratorEntity.DatabaseConfig;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@Service
public class DatabaseService {

    /**
     * 获取数据库中的所有表
     */
    public List<String> getTableList(DatabaseConfig dbConfig) {
        List<String> tables = new ArrayList<>();
        
        try (Connection connection = DriverManager.getConnection(
                dbConfig.getUrl(), dbConfig.getUsername(), dbConfig.getPassword())) {
            
            DatabaseMetaData metaData = connection.getMetaData();
            String[] types = {"TABLE"};
            
            // 根据不同数据库类型设置不同的schemaPattern参数
            String schemaPattern = null;
            String catalog = null;
            
            if ("oracle".equals(dbConfig.getDbType())) {
                // Oracle数据库使用用户名作为schema
                schemaPattern = dbConfig.getUsername().toUpperCase();
            } else if ("mysql".equals(dbConfig.getDbType())) {
                // MySQL从URL中提取数据库名作为catalog
                String url = dbConfig.getUrl();
                if (url.contains("?")) {
                    url = url.substring(0, url.indexOf("?"));
                }
                if (url.contains("/")) {
                    catalog = url.substring(url.lastIndexOf("/") + 1);
                }
            } else if ("sqlserver".equals(dbConfig.getDbType())) {
                // SQL Server使用用户名作为schema，同时catalog设置为数据库名
                schemaPattern = "dbo"; // SQL Server默认schema通常是dbo
                
                // 从URL中提取数据库名作为catalog
                String url = dbConfig.getUrl();
                if (url.contains(";")) {
                    String[] parts = url.split(";");
                    for (String part : parts) {
                        if (part.toLowerCase().startsWith("databasename=")) {
                            catalog = part.substring(part.indexOf("=") + 1);
                            break;
                        }
                    }
                }
            }
            
            ResultSet resultSet = metaData.getTables(catalog, schemaPattern, "%", types);
            
            while (resultSet.next()) {
                String tableName = resultSet.getString("TABLE_NAME");
                tables.add(tableName);
            }
            
        } catch (Exception e) {
            throw new RuntimeException("获取表列表失败: " + e.getMessage(), e);
        }
        
        return tables;
    }

    /**
     * 测试数据库连接
     */
    public boolean testConnection(DatabaseConfig dbConfig) {
        try (Connection connection = DriverManager.getConnection(
                dbConfig.getUrl(), dbConfig.getUsername(), dbConfig.getPassword())) {
            return connection.isValid(5); // 5秒超时
        } catch (Exception e) {
            return false;
        }
    }
}