import { CouchDb } from '@app/event-emitter/couchdb-datasources/couchdb';
import { Injectable, Logger } from '@nestjs/common';
import nano from 'nano';
import { UserMetaInfoModel } from 'src/models/user-meta-info.model';
import configuration from '../configs/app';

const config = configuration();

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

  static async getDatasource(): Promise<nano.DocumentScope<UserMetaInfoModel>> {
    if (UserMetaInfo.db) {
      return UserMetaInfo.db;
    }
    const n = CouchDb.getCouchDb();
    const userMetaInfoDbName =
      config.couchDb.dbs.userMetaInfo || 'user_meta_info';
    const dbs = await n.db.list();
    if (!dbs.includes(userMetaInfoDbName)) {
      await n.db.create(userMetaInfoDbName);
    }
    UserMetaInfo.db = await n.db.use(userMetaInfoDbName);
    UserMetaInfo.logger.log(
      `Connected to user_meta_info db - ${userMetaInfoDbName}`,
    );
    return UserMetaInfo.db;
  }

  async getDatasource(): Promise<nano.DocumentScope<UserMetaInfoModel>> {
    return await UserMetaInfo.getDatasource();
  }
}
