/**
 * Connection Resolver
 *
 * Resolve database connection info untuk audit-table-runner dari multiple sources:
 * 1. CLI args (object args dengan field dbHost, dbPort, dbUser, dbPassword, dbName)
 * 2. Environment variables RESTFORGE_DB_*
 * 3. Return null → caller akan masuk dry-run mode (tidak eksekusi DDL)
 *
 * @module lib/migration/connection-resolver
 */

const SUPPORTED_DIALECTS = ['postgres', 'mysql', 'oracle'];

/**
 * Resolve connection info berdasarkan dialect dan args.
 * @param {string} dialect - 'postgres' | 'mysql' | 'oracle'
 * @param {Object} [args] - CLI args object (opsional)
 * @returns {Object|null} Connection info atau null jika tidak bisa di-resolve
 */
function resolveConnectionInfo(dialect, args = {}) {
  if (!SUPPORTED_DIALECTS.includes(dialect)) {
    return null;
  }

  const env = process.env;

  const host = args.dbHost || env.RESTFORGE_DB_HOST;
  const user = args.dbUser || env.RESTFORGE_DB_USER;
  const password = args.dbPassword || env.RESTFORGE_DB_PASSWORD;
  const database = args.dbName || env.RESTFORGE_DB_NAME;

  // Minimum requirement: host, user, database
  if (!host || !user || !database) {
    return null;
  }

  const port = parseInt(
    args.dbPort || env.RESTFORGE_DB_PORT || defaultPort(dialect),
    10
  );

  const info = {
    host,
    port,
    user,
    password: password || '',
    database
  };

  // Oracle: optional connectString (override host:port/database)
  if (dialect === 'oracle') {
    const connectString = args.dbConnectString || env.RESTFORGE_DB_CONNECT_STRING;
    if (connectString) {
      info.connectString = connectString;
    }
  }

  return info;
}

function defaultPort(dialect) {
  if (dialect === 'mysql') return 3306;
  if (dialect === 'oracle') return 1521;
  return 5432;
}

module.exports = {
  resolveConnectionInfo
};
