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

const config = configuration();

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

  static async getDatasource(): Promise<
    nano.DocumentScope<RedmineTypes.Issue>
  > {
    if (Issues.initialized) {
      return Issues.issuesDb;
    }
    Issues.initialized = true;
    const n = CouchDb.getCouchDb();
    const issueDbName = config.couchDb?.dbs.issues || 'issues';
    const dbs = await n.db.list();
    if (!dbs.includes(issueDbName)) {
      await n.db.create(issueDbName);
    }
    Issues.issuesDb = await n.db.use(issueDbName);
    Issues.logger.log(`Connected to issues db - ${issueDbName}`);
    return Issues.issuesDb;
  }

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