import { DatabaseConnectorFactory } from '../database/DatabaseConnectorFactory';
import { ConnectionConfig, QueryResult } from '../interfaces/DatabaseConnector';
import { ConnectionTestResult, TableInfo } from '../types/externalDbTypes';

export class DbConnectionManager {
  static async testConnection(
    connectionId: number,
    dbType: string,
    config: ConnectionConfig
  ): Promise<ConnectionTestResult> {
    const connector = await DatabaseConnectorFactory.createConnector(dbType, config, connectionId);
    try {
      return await connector.testConnection();
    } finally {
      await DatabaseConnectorFactory.closeConnector(connectionId, dbType); // Close after test
    }
  }

  static async executeQuery(
    connectionId: number,
    dbType: string,
    config: ConnectionConfig,
    query: string
  ): Promise<QueryResult> {
    const connector = await DatabaseConnectorFactory.createConnector(dbType, config, connectionId);
    try {
      return await connector.executeQuery(query);
    } finally {
      await DatabaseConnectorFactory.closeConnector(connectionId, dbType);
    }
  }

  static async getTables(
    connectionId: number,
    dbType: string,
    config: ConnectionConfig
  ): Promise<TableInfo[]> {
    const connector = await DatabaseConnectorFactory.createConnector(dbType, config, connectionId);
    try {
      return await connector.getTables();
    } finally {
      await DatabaseConnectorFactory.closeConnector(connectionId, dbType);
    }
  }

  static async getColumns(
    connectionId: number,
    dbType: string,
    config: ConnectionConfig,
    tableName: string
  ): Promise<any[]> {
    const connector = await DatabaseConnectorFactory.createConnector(dbType, config, connectionId);
    try {
      return await connector.getColumns(tableName);
    } finally {
      await DatabaseConnectorFactory.closeConnector(connectionId, dbType);
    }
  }
}