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

/**
  * GM账号和用户组关系接口
*/
@index({ uid: 1, serverId: 1, groupId: 1 })

export default class GMUserGroup extends BaseModel {
  @prop({ required: true })
  uid: number;

  @prop({ required: true })
  serverId: number;

  @prop({ required: true })
  groupId: number;

  public static async getUserGroupByUid(uid: number, serverId: number, lean = true) {
    const user: GMUserGroupType[] = await GMUserGroupModel.find({uid, serverId}).lean(lean);
    return user;
  }

  public static async removeUserGroup(uid: number, serverId: number, groups: Array<number>) {
    const user = await GMUserGroupModel.deleteMany({uid, serverId, groupId: {$in: groups}});
    return user;
  }

  public static async addUserGroup(uid: number, serverId: number, groupId: number, lean = true) {
    const result: GMUserGroupType = await GMUserGroupModel.findOneAndUpdate({uid, serverId, groupId}, {}, {new:true, upsert:true}).lean(lean);
    return result;
  }
}

export const GMUserGroupModel = getModelForClass(GMUserGroup);

export interface GMUserGroupType extends Pick<DocumentType<GMUserGroup>, keyof GMUserGroup>{};