import { DbConnection } from './ConnectionManager';
import { GetSecretValueCommand, SecretsManagerClient } from '@aws-sdk/client-secrets-manager';

export async function getConnectionInfo(config: {
  databaseConnectionSecret?: string | false;
  databaseConnectionString?: string | false;
}): Promise<DbConnection | string> {
  if (config.databaseConnectionSecret) {
    return await getSecret(config.databaseConnectionSecret);
  }

  if (config.databaseConnectionString) {
    return config.databaseConnectionString;
  }

  throw new Error(`No db connection info available`);
}

async function getSecret(id: string) {
  const client = new SecretsManagerClient({});

  const result = await client.send(new GetSecretValueCommand({ SecretId: id }));

  if (result.SecretString === undefined) {
    throw new Error('secret could not be found');
  }

  const info = JSON.parse(result.SecretString);

  return {
    user: info.username,
    password: info.password,
    host: info.host,
    port: info.port,
    database: info.dbname,
  };
}
