import { RedmineTypes } from '../models/redmine-types';
import { Injectable, Logger } from '@nestjs/common';
import { Users } from '../couchdb-datasources/users';
import nano from 'nano';
import { Timestamped } from '../models/timestamped';
import { TimestampNowFill } from '../utils/timestamp-now-fill';

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

  constructor(private users: Users) {}

  async saveUser(
    user: RedmineTypes.User,
  ): Promise<RedmineTypes.User & Timestamped> {
    this.logger.debug(`Saving user ${user.id} - ${user.login}`);
    const id = user.id;
    const userDb = await this.users.getDatasource();
    let prevUser: (nano.DocumentGetResponse & RedmineTypes.User) | null;
    try {
      prevUser = await userDb.get(String(id));
    } catch (ex) {
      prevUser = null;
    }
    const newUser: nano.DocumentGetResponse & RedmineTypes.User & Timestamped =
      TimestampNowFill({ ...(user as any), _id: String(id) });
    if (prevUser) {
      newUser._rev = prevUser._rev;
    }
    await userDb.insert(newUser);
    return newUser;
  }
}
