import { Injectable, Logger } from '@nestjs/common';
import * as nano from 'nano';
import configuration from '../configs/main-config';

const config = configuration();

@Injectable()
export class CouchDb {
  private static logger = new Logger(CouchDb.name);
  private static couchdb: nano.ServerScope | null = null;
  private static initialized = false;

  static getCouchDb(): nano.ServerScope | null {
    if (CouchDb.initialized) {
      return CouchDb.couchdb;
    }
    CouchDb.initialized = true;
    const url = config.couchDb?.url;
    if (!url) {
      return null;
    } else {
      const n = nano(url);
      CouchDb.logger.log(`CouchDb connected by url ${url} ...`);
      CouchDb.couchdb = n;
      return n;
    }
  }
}
