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

const config = configuration();

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

  static async getDatasource(): Promise<
    nano.DocumentScope<DailyEccmReport.Models.Report>
  > {
    if (DailyEccmReportsDatasource.initilized) {
      return DailyEccmReportsDatasource.db;
    }
    DailyEccmReportsDatasource.initilized = true;
    const n = CouchDb.getCouchDb();
    const dbName = config.couchDb.dbs.eccmDailyReports;
    const dbs = await n.db.list();
    if (!dbs.includes(dbName)) {
      await n.db.create(dbName);
    }
    DailyEccmReportsDatasource.db = await n.db.use(dbName);
    DailyEccmReportsDatasource.initilized = true;
    DailyEccmReportsDatasource.logger.log(
      `Connected to eccm-daily-reports db - ${dbName}`,
    );
    return DailyEccmReportsDatasource.db;
  }

  async getDatasource(): Promise<
    nano.DocumentScope<DailyEccmReport.Models.Report>
  > {
    return await DailyEccmReportsDatasource.getDatasource();
  }
}
