// Sequelize database library
// https://sequelize.org/docs/v6/

import {Sequelize} from 'sequelize';
import log from '../util/logger';

export async function connectToDB(
  db: string,
  login: string,
  password: string,
): Promise<Sequelize> {
  // Option 3: Passing parameters separately (other dialects)
  // https://sequelize.org/docs/v6/getting-started/#connecting-to-a-database
  const sequelize = new Sequelize(db, login, password, {
    host: 'localhost',
    dialect: 'postgres', // one of 'mysql' | 'postgres' | 'sqlite' | 'mariadb' | 'mssql' | 'db2' | 'snowflake' | 'oracle'
    logging: (msg) => log.info(msg),
  });

  try {
    await sequelize.authenticate();
    log.info('Connection has been established successfully.');
    console.log('Connection has been established successfully.');
  } catch (error) {
    log.error('Unable to connect to the database:', error);
    console.error('Unable to connect to the database:', error);
  }

  return sequelize;
}
