import { ApiCall } from "tsrpc";
import { MongodbCollections } from '../../module/mongodb';
import { GongHuiFun } from '../../public/gonghui/gonghui';
import { GHManage } from '../../public/gonghui/manage';
import { PlayerFun } from '../../public/player';
import { ReqCreate, ResCreate } from "../../shared/protocols/gonghui/PtlCreate";

export default async function (call: ApiCall<ReqCreate, ResCreate>) {
    if ((call.conn.gud.ghExitTime || 0) + G.gc.com.Guild_CD.value > G.time) {
        return call.error(globalThis.lng.gonghui_5);
    }

    if (call.conn.gud.ghId) return call.error(globalThis.lng.gonghui_6);

    if (call.conn.gud.vip < G.gc.shili_com.createVip) return call.error(globalThis.lng.gonghui_7);

    await PlayerFun.checkNeedIsMeet(call, G.gc.shili_com.createNeed);

    await GongHuiFun.checkSetArgs(call.req);

    await PlayerFun.cutNeed(call, G.gc.shili_com.createNeed);

    const data: MongodbCollections['gonghui'] = {
        lv: 1,
        exp: 0,
        name: call.req.name,
        players: [
            {
                uid: call.uid,
                level: 1,
                joinTime: G.time
            }
        ],
        setting: {
            ...call.req.setting,
            joinLv: G.gc.shili_com.defaultJoinLv,
            notice: G.gc.shili_com.defaultNotice,
            autoJoin: G.gc.shili_com.defaultAutoJoin,
        },
        createTime: G.time,
        createPlayer: { name: call.conn.gud.name, uid: call.uid },
    };
    const _id = await GongHuiFun.db.insertOne(data);

    await GHManage.addNew({ ...data, _id: G.mongodb.conversionId(_id.insertedId) });

    await PlayerFun.addAttr(call, { ghId: G.mongodb.conversionId(_id.insertedId), ghName: call.req.name, ghLevel: 1 });
    
    call.succ({});
}