import { ApiCall } from "tsrpc";
import { PlayerFun } from '../../../public/player';
import { ReqBuy, ResBuy } from "../../../shared/protocols/event/xianshizhaomu/PtlBuy";
import { xszmdb } from './ApiOpen';

export default async function (call: ApiCall<ReqBuy, ResBuy>) {
    let conf = G.gc.xianshizhaomu.gift[call.req.index];
    if (!conf || conf.payId) return call.error('', { code: -1 });

    let db = await xszmdb().findOne({ uid: call.uid, type: 'xianshizhaomu' });
    if (db?.recordBuy?.[call.req.index] >= conf.num) return call.error('', { code: -1 });

    if (conf.need.length > 0) {
        await PlayerFun.checkNeedIsMeet(call, conf.need);
        await PlayerFun.cutNeed(call, conf.need);
    }

    await PlayerFun.sendPrize(call, conf.prize);

    xszmdb().updateOne(
        { uid: call.uid, type: 'xianshizhaomu' },
        { $inc: G.mongodb.createTreeObj({ key: `recordBuy.${call.req.index}`, val: 1 }) },
        { upsert: true }
    );

    call.succ({
        prize: conf.prize
    });
}