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

/**
  * 服务器分战区
*/
@index({ time: -1, serverId: -1 })
export default class GVGServerGroup extends BaseModel {

    @prop({ required: true, default: 1 })
    serverId: number;             // 服务器id

    @prop({ required: true, default: 1 })
    groupId: number;             // 战区id

    @prop({ required: true, default: 0 })
    time: number;               // 生效时间

    public static async findByTime(time: number) {
      const serverGroup: { serverId: number, groupId: number }[] = await GVGServerGroupModel.aggregate([
        { $match: { time: { $lte: time } } },
        { $sort: { time: -1 } },
        { $group: { _id: "$serverId", serverId: { $first: "$serverId" }, groupId: { $first: "$groupId" }, time: { $first: "$time" }} },
        { $sort: { _id: -1 } },
        { $project: { _id: 0, serverId: "$serverId", groupId: "$groupId", time: "$time" } }
      ]);
      return serverGroup;
    }

    public static async updateByServerId(serverId: number, groupId: number, time: number) {
      const result: GVGServerGroupType = await GVGServerGroupModel.findOneAndUpdate({ serverId, time }, { $set: { groupId } }, { new: true, upsert: true }).lean();
      return result
    }
}

export let GVGServerGroupModel = getModelForClass(GVGServerGroup);

export interface GVGServerGroupType extends Pick<DocumentType<GVGServerGroup>, keyof GVGServerGroup> {
    id: number;
};
export type GVGServerGroupUpdate = Partial<GVGServerGroupType>; // 将所有字段变成可选项
