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

@index({ roleId: 1, warId: 1 })
export default class PvpSaveData extends BaseModel {
    @prop({ required: true })
    roleId: string;					// 角色 id
    
    @prop({ required: true })
    warId: number;					// 关卡id

    @prop({ required: true })
    buff: number;					// 地图buff

    @prop({ required: true, default: [], _id: false, type: DefenseHeroInSaveData })
    heroes: DefenseHeroInSaveData[];

    
    public static async createSaveData(roleId: string, warId: number, buff: number, heroes: DefenseHeroInSaveData[]) {
        const result: PvpSaveDataType = await PvpSaveDataModel.findOneAndUpdate({ roleId, warId }, { $set: { buff, heroes } }, { new: true, upsert: true }).lean();
        return result;
    }

    public static async findByRoleId(roleId: string) {
        const result: PvpSaveDataType[] = await PvpSaveDataModel.find({ roleId }).lean();
        return result;
    }

    public static async removeBySub(roleId: string, subHid: number) {   
        await PvpSaveDataModel.updateMany({ roleId }, { $pull: { heroes: { actorId: subHid } } });
    }
    
}

export const PvpSaveDataModel = getModelForClass(PvpSaveData);

export interface PvpSaveDataType extends Pick<DocumentType<PvpSaveData>, keyof PvpSaveData> { };
export type pvpSaveDataUpdate = Partial<PvpSaveDataType>;