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;
  private static url: string | null = null;

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

  static getCouchDbUrl(): string | null {
    return this.url;
  }
}
