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

/**
  * 玩家购买商店记录表，每个商品一条，每次刷新新建一条
**/
@modelOptions({ schemaOptions: { id: false } })
@index({ roleId: 1, shop: 1, type: 1 })

export default class UserShopType extends BaseModel {
    @prop({ required: true })
    roleId: string;					// 玩家id

    @prop({ required: true })
    shop: number; 				// 商店id

    @prop({ required: true })
    type: number; 				// 商店页签id

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

    public static async findByRoleId(roleId: string) {
        let rec: UserShopTypeType[] = await UserShopTypeModel.find({ roleId }).lean();
        return rec;
    }

    public static async findByType(roleId: string, shop: number, type: number) {
        let rec: UserShopTypeType = await UserShopTypeModel.findOne({ roleId, shop, type }).lean();
        return rec;
    }

    public static async read(roleId: string, shop: number, type: number) {
        let rec: UserShopTypeType[] = await UserShopTypeModel.findOneAndUpdate({ roleId, shop, type }, { $set: {readTime: nowSeconds()} }, { new: true, upsert: true }).lean();
        return rec;
    }
}

export const UserShopTypeModel = getModelForClass(UserShopType);

export interface UserShopTypeType extends Pick<DocumentType<UserShopType>, keyof UserShopType> { }
export type UserShopTypeParam = Partial<UserShopTypeType>;
