import BaseModel from './BaseModel';
import { index, getModelForClass, prop, DocumentType } from '@typegoose/typegoose';

/**
  * 自增 ID
*/
@index({ name: 1 })
export default class Counter extends BaseModel {

  @prop({ required: true })
  name: string;

  @prop({ required: true, default: 1 })
  seq: number;

  public static async getNewCounter(param:{name: string, def: number}, lean = true) {
    let {name, def:defaultVal} = param;
    let counter: CounterType = await CounterModel.findOneAndUpdate({ name }, { $inc: { seq: 1 } }, { new: true, upsert: true }).lean(lean);
    if(!counter || (counter&&counter.seq == 1) && defaultVal != 1) {
      counter = await CounterModel.findOneAndUpdate({ name }, { $set: { seq: defaultVal } }, { new: true, upsert: true }).lean(lean);
    }
    return counter?.seq;
  }

  public static async getCounter(param:{name: string, def: number}, lean = true) {
    let {name} = param;
    let counter: CounterType = await CounterModel.findOne({ name }).lean(lean);
    return counter?.seq||0;
  }

}

export const CounterModel = getModelForClass(Counter);

export interface CounterType extends Pick<DocumentType<Counter>, keyof Counter>{};