import { OptionalId, WithId } from 'mongodb';
import { ApiCall } from "tsrpc";
import { CollectionPlayerInfo } from '../../module/collection_palyerInfo';
import { joinFightData } from '../../shared/fightControl/fightType';
import { ReqOpen, ResOpen } from "../../shared/protocols/conglinshoulie/PtlOpen";
import { PublicShared } from '../../shared/public/public';

export default async function (call: ApiCall<ReqOpen, ResOpen>) {
    let db = await clslDb().findOne({ uid: call.uid, type: 'clsl' });
    let { _id, uid, type, ...ops } = db || {} as WithId<OptionalId<CollectionPlayerInfo<"clsl">>>;

    if (!db || ops?.refreshTime < PublicShared.getToDayZeroTime()) {

        let change: Partial<typeof ops> = {
            refreshTime: G.time,
            useFightNum: 0,
            recWinPrize: [],
            fightWinNum: 0,
            buyFightNum: 0
        };

        Object.assign(ops, change);

        clslDb().updateOne({ uid: call.uid, type: 'clsl' }, { $set: change }, { upsert: true });

        call.conn.getDefaultFightData().then(v => {
            G.clientCross.callApi('clsl/UpLoad', { uid: call.uid, info: v });
        });
    }

    call.succ({
        allStar: ops?.allStar || 0,
        buyFightNum: ops?.buyFightNum || 0,
        useFightNum: ops?.useFightNum || 0,
        fightWinNum: ops?.fightWinNum || 0,
        recWinPrize: ops?.recWinPrize || []
    });
}

export function clslDb() {
    return G.mongodb.cPlayerInfo('clsl');
}

export async function addStar(call: ApiCall, star: number, info?: joinFightData) {
    clslDb().updateOne({ uid: call.uid, type: 'clsl' }, { $inc: { allStar: star } }, { upsert: true });
    G.clientCross.callApi('clsl/UpLoad', { uid: call.uid, allStar: star, info: info || await call.conn.getDefaultFightData() });
}