import BaseModel from './BaseModel';
import { index, getModelForClass, prop, DocumentType, modelOptions, Ref, mongoose } from '@typegoose/typegoose';
import GiftCode, { GiftCodeType } from './GiftCode';

/**
  * 举报记录
**/
@modelOptions({ schemaOptions: { id: false } })
@index({ roleId: 1, code: 1 })
export default class UserGiftCode extends BaseModel {

    @prop({ required: true, default: '' })
    roleId: string;           // 玩家id

    @prop({ required: true, default: '' })
    code: string;           // 兑换码

    @prop({ ref: 'GiftCode', type: mongoose.Schema.Types.ObjectId })
    giftCode: Ref<GiftCode>;
    
    // 根据code
    public static async findByCode(roleId: string, code: string) {
        let result: UserGiftCodeType = await UserGiftCodeModel.findOne({ roleId, code }).lean();
        return result;
    }
    
    public static async createCode(roleId: string, code: string, gitCode: GiftCodeType) {
      let result: UserGiftCodeType = await UserGiftCodeModel.findOneAndUpdate({ roleId, code }, { $setOnInsert: { gitCode: gitCode._id } }, { new: true, upsert: true}).lean()
      return result;
    }
}

export const UserGiftCodeModel = getModelForClass(UserGiftCode);

export interface UserGiftCodeType extends Pick<DocumentType<UserGiftCode>, keyof UserGiftCode> { }
export type UserGiftCodeParam = Partial<UserGiftCodeType>;
