import path from 'path';
import { Connection, createConnection as ormCreateConnection } from 'typeorm';
import { SqliteConnectionOptions } from 'typeorm/driver/sqlite/SqliteConnectionOptions';
import { appPath } from './app-path';

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

type MyConnectionOptions = { [key in Databases]?: SqliteConnectionOptions };

const databaseDir = path.resolve(appPath, 'database');
const connectionOptions: MyConnectionOptions = Object.values(Databases).reduce(
  (prev: MyConnectionOptions, database: Databases) => {
    prev[database] = {
      name: database,
      type: 'sqlite',
      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}`,
      },
    };
    return prev;
  },
  {}
);

const connections: {
  [key in Databases]?: Connection;
} = {};

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

export function getConnection(database: Databases): Promise<Connection> {
  if (connections[database] === undefined) {
    return createConnection(database);
  }
  return Promise.resolve(connections[database]);
}
