import {closeAllDatabases, databases, DBObject, getDatabase} from './getDB';
import DBSchemas, {SkipDBSchemas} from './schemas';
import {databaseConf, databaseNameSuffix, mergeDBName} from './types';

export const initDatabases = (): Promise<void> => {
  return new Promise(async (resolve, reject) => {
    closeAllDatabases();

    for (const key in DBSchemas) {
      const schema = DBSchemas[key as keyof typeof DBSchemas];
      const name = schema.details.name;

      if (SkipDBSchemas.includes(name)) continue;

      await initDatabase(schema);
    }
    resolve();
  });
};

export const initDatabase = async (
  schema: (typeof DBSchemas)[keyof typeof DBSchemas],
  fileSuffix?: string,
): Promise<string> => {
  const _nameObj: databaseNameSuffix = {
    name: schema.details.name,
    suffix: fileSuffix,
  };
  console.log('initDatabase', _nameObj);
  const name = mergeDBName(_nameObj);

  let dbObj: DBObject = {
    schema: schema,
    name,
    db: undefined,
  };

  databases[name] = dbObj;

  await getDatabase(_nameObj, true); // init Database
  return name;
};
