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

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

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