import { RedmineTypes } from '../models/redmine-types';
import { Injectable, Logger } from '@nestjs/common';
import nano from 'nano';
import { CouchDb } from './couchdb';
import configuration from '../configs/main-config';

const config = configuration();

@Injectable()
export class Users {
  private static logger = new Logger(Users.name);
  private static usersDb = null;
  private static initialized = false;

  static async getDatasource(): Promise<nano.DocumentScope<RedmineTypes.User>> {
    if (Users.initialized) {
      return Users.usersDb;
    }
    Users.initialized = true;
    const n = CouchDb.getCouchDb();
    const usersDbName = config.couchDb?.dbs.users;
    const dbs = await n.db.list();
    if (!dbs.includes(usersDbName)) {
      await n.db.create(usersDbName);
    }
    Users.usersDb = await n.db.use(usersDbName);
    Users.logger.log(`Connected to users db - ${usersDbName}`);
    return Users.usersDb;
  }

  async getDatasource(): Promise<nano.DocumentScope<RedmineTypes.User>> {
    return await Users.getDatasource();
  }
}
