import path from 'path';
import { Connection, createConnection as ormCreateConnection } from 'typeorm';
import { BetterSqlite3ConnectionOptions } from 'typeorm/driver/better-sqlite3/BetterSqlite3ConnectionOptions';
import { appPath } from './app-path';

export enum Database {
  LIBRARY = 'library',
  STORE = 'store',
}

type MyConnectionOptions = { [key in Database]: BetterSqlite3ConnectionOptions };

const databaseDir = path.resolve(appPath, 'database');

/**
 * @see ormconfig.yml in the root folder
 */
function getConnectionOptionsFor(database: Database): BetterSqlite3ConnectionOptions {
  return {
    name: database,
    type: 'better-sqlite3',
    database: path.resolve(databaseDir, `${database}.db`),
    cache: true,
    entities: [`./src/main/entities/${database}/*.js`],
    migrations: [`./src/main/migrations/${database}/*.js`],
    cli: {
      migrationsDir: `./src/main/migrations/${database}`,
    },
  };
}

const connectionOptions: MyConnectionOptions = {
  [Database.LIBRARY]: getConnectionOptionsFor(Database.LIBRARY),
  [Database.STORE]: getConnectionOptionsFor(Database.STORE),
};

function createConnection(database: Database): Promise<Connection> {
  let connection: Connection;
  return ormCreateConnection(connectionOptions[database])
    .then((c) => {
      connection = c;
      return c.runMigrations();
    })
    .then(() => connection);
}

const connections = {
  [Database.LIBRARY]: createConnection(Database.LIBRARY),
  [Database.STORE]: createConnection(Database.STORE),
};

export function getConnection(database: Database): Promise<Connection> {
  return Promise.resolve(connections[database]);
}
