import { Injectable, Logger } from '@nestjs/common';
import { randomUUID } from 'crypto';
import nano from 'nano';
import { Subject } from 'rxjs';
import { Changes } from 'src/couchdb-datasources/changes';
import { Change } from 'src/models/change.model';

@Injectable()
export class ChangesCacheWriterService {
  private logger = new Logger(ChangesCacheWriterService.name);

  subject = new Subject<Change>();

  constructor(private changes: Changes) {}

  async saveChange(change: Change): Promise<void> {
    this.logger.debug(
      `saveChange started, ` +
        `issue_id = ${change.issue_id}, ` +
        `initiator.name = ${change.initiator.name}`,
    );
    if (!change) {
      this.logger.debug(`saveChange successed, no data for saving`);
      return;
    }
    const changesDb = await this.changes.getDatasource();
    if (!changesDb) {
      this.logger.error(`saveChange failed, changesDb is undefined or null`);
      return;
    }
    const item: Change & nano.MaybeDocument = { ...change };
    item._id = this.getId();
    if (!item) {
      this.logger.debug(`saveChange successed, no data for saving`);
      return;
    }
    try {
      await changesDb.insert(item);
    } catch (ex) {
      this.logger.error(`saveChange failed, error = ${ex}`);
      return;
    }
    this.subject.next(change);
    this.logger.debug(
      `saveChange successed, ` +
        `issue_id = ${change.issue_id}, ` +
        `initiator.name = ${change.initiator.name}`,
    );
  }

  private getId(): string {
    return randomUUID();
  }
}
