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

export class Report {
    @prop({ required: true })
    roleName: string;

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

    @prop({ required: true })
    id: number;//捐献类型id 1-铜钱 2-元宝 3-至尊捐赠

    @prop({ required: true })
    fund: number;//捐献数
}

@index({ guildCode: 1 })
export default class Donation extends BaseModel {
    
    @prop({ required: true })
    guildCode: string;

    @prop({ required: true, default: 0})
    donateFund: number;

    @prop({ required: true, type: Report, default:[], _id: false  })
    reports: Array<Report>;

    @prop({ required: true, default: 0})
    refTime: number;

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

    public static async findOrCreateDonationByRefTime(guildCode: string, refTime: number, donationLv: number ) {
        const result: DonationType = await DonationModel.findOneAndUpdate({ guildCode, refTime }, { $setOnInsert: { donateFund: 0, reports: [], donationLv  }}, { upsert: true, new: true }).lean();
        return result;
    }

    public static async donate(guildCode: string, refTime: number, donateFund: number, reports: Report, donationLv: number) {
        const result: DonationType = await DonationModel.findOneAndUpdate({ guildCode, refTime }, { $setOnInsert: { donationLv }, $inc:{ donateFund }, $push: { reports }}, {upsert: true, new: true}).lean();
        return result;
    }

    public static async findDonationByRefTime(guildCode: string, refTime: number ) {
        const result: DonationType = await DonationModel.findOne({ guildCode, refTime }).lean();
        return result;
    }
}

export const DonationModel = getModelForClass(Donation);

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