import { CacheTTL, Injectable } from '@nestjs/common';
import { UserMetaInfo } from 'src/couchdb-datasources/user-meta-info';
import { UserMetaInfoModel } from 'src/models/user-meta-info.model';
import nano from 'nano';

@Injectable()
export class UserMetaInfoService {
  constructor(private userMetaInfo: UserMetaInfo) {}

  @CacheTTL(60)
  async findByRedmineId(id: number): Promise<UserMetaInfoModel | null> {
    const db = await this.userMetaInfo.getDatasource();
    try {
      return await db.get(String(id));
    } catch (ex) {
      return null;
    }
  }

  @CacheTTL(60)
  async findByTelegramId(id: number): Promise<UserMetaInfoModel | null> {
    const db = await this.userMetaInfo.getDatasource();
    try {
      const resp = await db.find({
        selector: { telegram_chat_id: id },
        limit: 1,
      });
      return resp.docs && resp.docs[0] ? resp.docs[0] : null;
    } catch (ex) {
      return null;
    }
  }

  async save(data: UserMetaInfoModel): Promise<void> {
    const id = String(data.user_id);
    const db = await this.userMetaInfo.getDatasource();
    let item: (nano.MaybeDocument & UserMetaInfoModel) | null = null;
    const newItem: nano.MaybeDocument & UserMetaInfoModel = {
      _id: id,
      ...data,
    };
    try {
      item = await db.get(id);
    } catch (ex) {}
    if (item) {
      newItem._id = item._id;
      newItem._rev = item._rev;
    }
    await db.insert(newItem);
  }

  async delete(data: UserMetaInfoModel): Promise<void> {
    const id = String(data.user_id);
    const db = await this.userMetaInfo.getDatasource();
    let item: (nano.MaybeDocument & UserMetaInfoModel) | null = null;
    try {
      item = await db.get(id);
    } catch (ex) {}
    if (item) {
      await db.destroy(item._id, item._rev);
    }
  }
}
