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

export default class RegionWhiteList extends BaseModel {

    @prop({ required: true })
    code: string;                    // 编码

    @prop({ required: true })
    regionId: number;              // 大区区号

    @prop({ required: true })
    env: string;		            // 环境变量

    @prop({ required: true, enum: WHITE_LIST_TYPE })
    type: WHITE_LIST_TYPE;		            // 环境变量

    @prop({ required: true })
    ip: string;		                // ip
    
    @prop({ required: true })
    uid: number;                    // 玩家uid

    public static async checkIp(env: string, ip: string) {
        const rec = await WhiteListModel.exists({ env, ip });
        return rec;
    }

    public static async checkUid(env: string, uid: number) {
        const rec = await WhiteListModel.exists({ env, uid });
        return rec;
    }

    public static async findByRegionId(regionId: number) {
        const rec: WhiteListModelType[] = await WhiteListModel.find({ regionId });
        return rec;
    }

    public static async updateWhiteList(code: string, params: WhiteListModelTypeParam) {
        const rec: WhiteListModelType = await WhiteListModel.findOneAndUpdate({ code }, params, { new: true, upsert: true }).lean();
        return rec;
    }

    public static async deleteWhiteList(code: string) {
        const rec: WhiteListModelType = await WhiteListModel.findOneAndDelete({ code }).lean();
        return rec;
    }
}

export let WhiteListModel = getModelForClass(RegionWhiteList)

export interface WhiteListModelType extends Pick<DocumentType<RegionWhiteList>, keyof RegionWhiteList> { }
export type WhiteListModelTypeParam = Partial<WhiteListModelType>; // 将所有字段变成可选项