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

/**
  * 自增 ID
*/
@index({ name: 1 })
export default class CounterAll 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 CounterAllModal.findOneAndUpdate({ name }, { $inc: { seq: 1 } }, { new: true, upsert: true }).lean(lean);
    if(!counter || (counter&&counter.seq == 1) && defaultVal != 1) {
      counter = await CounterAllModal.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, def:defaultVal} = param;
    let counter: CounterType = await CounterAllModal.findOne({ name }).lean(lean);
    return counter?.seq||defaultVal;
  }

}

export let CounterAllModal: ReturnModelType<typeof CounterAll, {}>;
export function loadCounterModal(connect: mongoose.Connection) {
    CounterAllModal = getModelForClass(CounterAll, {
        existingConnection: connect
    });
}

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