import { GMUserModel } from '@db/GMUser';
import { GMUserGroupModel } from '@db/GMUserGroup'
import { GMGroupModel } from '@db/GMGroup'
import { GMRecordModel } from '@db/GMRecord'
import { ApiModel } from '@db/Api';
import { STATUS } from '@consts';

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.WRONG_PARMS);
      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;
    }
    const url = ctx.request.url;
    let apiResult = await ApiModel.getApi(url);
    if(!apiResult) {
      ctx.body = ctx.service.utils.resResult(STATUS.GM_MISS_API);
      return;
    }
    let userGroups = await GMUserGroupModel.getUserGroupByUid(user.uid, 1);
    let flag = 0;
    for(let userGroup of userGroups) {
      let { groupId } = userGroup;
      let group = await GMGroupModel.getGroupById(groupId);
      if(group) {
        if(group.apis.includes(apiResult.apiId)) {
          flag = 1; break;
        }
      }
    }
    if(flag != 1) {
      ctx.body = ctx.service.utils.resResult(STATUS.GM_NO_AUTHORITY_GET);
      return;
    }
    ctx.user = user;
    await next();
    if(ctx.request.method == "POST") {
      await GMRecordModel.createRecord(user?user.uid:0, ctx.request.url, JSON.stringify(ctx.request.body||{}), JSON.stringify(ctx.body||{}));
    }
  };
};

