import { CouchDb } from '@app/event-emitter/couchdb-datasources/couchdb';
import { Injectable, Logger } from '@nestjs/common';
import nano from 'nano';
import { Change } from 'src/models/change.model';
import configuration from '../configs/app';

const config = configuration();

@Injectable()
export class Changes {
  private static logger = new Logger(Changes.name);
  private static changesDb = null;
  private static initilized = false;

  static async getDatasource(): Promise<nano.DocumentScope<Change>> {
    if (Changes.initilized) {
      return Changes.changesDb;
    }
    Changes.initilized = true;
    const n = CouchDb.getCouchDb();
    const changesDbName = config.couchDb.dbs.changes;
    const dbs = await n.db.list();
    if (!dbs.includes(changesDbName)) {
      await n.db.create(changesDbName);
    }
    Changes.changesDb = await n.db.use(changesDbName);
    Changes.initilized = true;
    Changes.logger.log(`Connected to changes db - ${changesDbName}`);
    return Changes.changesDb;
  }

  async getDatasource(): Promise<nano.DocumentScope<Change>> {
    return await Changes.getDatasource();
  }
}
