import { UpdateFilter } from 'mongodb';
import { ApiCall } from "tsrpc";
import { CollectionEvent } from '../../../module/collection_event';
import { ReqOpen, ResOpen } from "../../../shared/protocols/event/xianshizhaomu/PtlOpen";
import { PublicShared } from '../../../shared/public/public';

export default async function (call: ApiCall<ReqOpen, ResOpen>) {

    let db = await xszmdb().findOne({ uid: call.uid, type: 'xianshizhaomu' });
    let update: UpdateFilter<CollectionEvent<'xianshizhaomu'>>;
    let res: Partial<ResOpen> = {};

    if (!db || db?.refreshTime < PublicShared.getToDayZeroTime(G.time)) {
        update = {
            $set: {
                refreshTime: G.time,
                recordBuy: {}
            }
        };
        res.recordBuy = {};
    }

    update && xszmdb().updateOne({ uid: call.uid, type: 'xianshizhaomu' }, update, { upsert: true });

    call.succ({
        recordNum: db?.recordNum || 0,
        recordBuy: db?.recordBuy || res.recordBuy,
        recordPrize: db?.recordPrize || [],
        recordOneNum: db?.recordOneNum || 0,
        recordDuihuan: db?.recordDuihuan || {}
    });
}

export function xszmdb() {
    return G.mongodb.cEvent('xianshizhaomu');
}