import BaseModel from './BaseModel';
import { index, getModelForClass, prop, DocumentType } from '@typegoose/typegoose';
import { genCode } from '../pubUtils/util';
import { GUILD_REC_TYPE } from '../consts';
import { nowSeconds } from '../pubUtils/timeUtil';

@index({ guildCode: 1 })
export default class GuildRec extends BaseModel {

    @prop({ required: true })
    recCode: string;

    @prop({ required: true, select: false })
    roleId: string;

    @prop({ required: true })
    guildCode: string;

    @prop({ required: true, default: GUILD_REC_TYPE.JOIN_GUILD, enum: GUILD_REC_TYPE })
    type: number;

    @prop({ required: true, type: String, default: [] })
    params: string[];

    @prop({ required: true, default: nowSeconds() })
    createTime: number;

    public static async createGuildRec(roleId: string, guildCode: string, type: number, params: string[]) {
        const doc = new GuildRecModel();
        const update = Object.assign(doc.toJSON(), { roleId, guildCode, type, params, createTime: nowSeconds() });
        delete update._id;
        const recCode = genCode(10);
        const result: GuildRecType = await GuildRecModel.findOneAndUpdate({ recCode }, update, { upsert: true, new: true }).lean();
        return result;
    }

    public static async getGuildRec(guildCode: string, time: number) {
        const result: GuildRecType[] = await GuildRecModel.find({ guildCode, createTime: { $gte: time } }).sort({createTime: -1}).lean();
        return result;
    }
}

export const GuildRecModel = getModelForClass(GuildRec);

export interface GuildRecType extends Pick<DocumentType<GuildRec>, keyof GuildRec> { };