import { ApiCall } from "tsrpc";
import { PlayerFun } from '../../../public/player';
import { ReqRecPrize, ResRecPrize } from "../../../shared/protocols/gongyu/mingdao/PtlRecPrize";

export default async function (call: ApiCall<ReqRecPrize, ResRecPrize>) {
    let id = call.req.id;
    let recId = call.req.recId;

    if (!G.gc.mingdao[id]) return call.errorCode(-1);
    if (!G.gc.mingdao[id].reward[recId]) return call.errorCode(-2);
    if (call.conn.gud.shoucangping[id] < Number(recId)) return call.errorCode(-3);

    let recArr = (await G.mongodb.collection('mingdao').findOne({ uid: call.uid }))?.list?.[id]?.recPrize || [];
    if (recArr.includes(recId)) return call.errorCode(-4);

    await PlayerFun.sendPrize(call, [].concat(G.gc.mingdao[id].reward[recId]));

    G.mongodb.collection('mingdao').updateOne(
        { uid: call.uid },
        { $push: G.mongodb.createTreeObj({ key: `list.${id}.recPrize`, val: recId }) },
        { upsert: true }
    );

    call.succ({
        prize: [].concat(G.gc.mingdao[id].reward[recId])
    });
}