import { CouchDb } from '@app/event-emitter/couchdb-datasources/couchdb';
import nano from 'nano';
import { Injectable, Logger } from '@nestjs/common';
import configuration from '../configs/app';
import { DailyEccmUserComments } from 'src/reports/daily-eccm-user-comments.service';

const config = configuration();

@Injectable()
export class DailyEccmReportsUserCommentsDatasource {
  private static logger = new Logger(
    DailyEccmReportsUserCommentsDatasource.name,
  );
  private static db = null;
  private static initilized = false;

  static async getDatasource(): Promise<
    nano.DocumentScope<DailyEccmUserComments.Models.Item>
  > {
    if (DailyEccmReportsUserCommentsDatasource.initilized) {
      return DailyEccmReportsUserCommentsDatasource.db;
    }
    DailyEccmReportsUserCommentsDatasource.initilized = true;
    const n = CouchDb.getCouchDb();
    const dbName = config.couchDb.dbs.eccmDailyReportsUserComments;
    const dbs = await n.db.list();
    if (!dbs.includes(dbName)) {
      await n.db.create(dbName);
    }
    DailyEccmReportsUserCommentsDatasource.db = await n.db.use(dbName);
    DailyEccmReportsUserCommentsDatasource.initilized = true;
    DailyEccmReportsUserCommentsDatasource.logger.log(
      `Connected to eccm_daily_reports_user_comments db - ${dbName}`,
    );
    return DailyEccmReportsUserCommentsDatasource.db;
  }

  async getDatasource(): Promise<
    nano.DocumentScope<DailyEccmUserComments.Models.Item>
  > {
    return await DailyEccmReportsUserCommentsDatasource.getDatasource();
  }
}
