import { GMUserModel } from '@db/GMUser';
import { GMGroupModel } from '@db/GMGroup'
import { GMRecordModel } from '@db/GMRecord'
import { GM_API_TYPE, STATUS } from '@consts';
import { gameData } from '@pubUtils/data';
import { nowSeconds } from '@pubUtils/timeUtil';

module.exports = () => {
  return async function tokenParser(ctx, next) {

    if (!ctx.request.headers || !ctx.request.headers.token) {
      console.error('token not found');
      ctx.body = ctx.service.utils.resResult(STATUS.TOKEN_ERR);
      return;
    }
    const user = await GMUserModel.getGmAccountByToken(ctx.request.headers.token);
    if (!user) {
      console.error('token invalid');
      ctx.body = ctx.service.utils.resResult(STATUS.TOKEN_ERR);
      return;
    }
    if((user?.expireTime||0) < nowSeconds()) {
      ctx.body = ctx.service.utils.resResult(STATUS.TOKEN_ERR);
      return;
    }

    const url = ctx.request.url;
    let dicApi = gameData.apiByUrl.get(url);
    if(!dicApi) {
      ctx.body = ctx.service.utils.resResult(STATUS.GM_MISS_API);
      return;
    }
    let group = await GMGroupModel.getGroupById(user.groupId);
    
    if(!group || !user.isEnable) {
      ctx.body = ctx.service.utils.resResult(STATUS.GM_NO_AUTHORITY_GET);
      return
    } 

    if(!group.apis.includes(0) && !group.apis.includes(dicApi.id)) {
      ctx.body = ctx.service.utils.resResult(STATUS.GM_NO_AUTHORITY_GET);
      return
    }
    
    ctx.user = user;
    await next();
    if(dicApi.type != GM_API_TYPE.find) {
       GMRecordModel.createRecord(user?user.uid:0, ctx.app.config.realEnv, ctx.request.url, JSON.stringify(ctx.request.body||{}), JSON.stringify(ctx.body||{}));
    }
  };
};

