import { Middleware } from '@midwayjs/decorator';
import * as _ from 'lodash';
import { NextFunction, Context } from '@midwayjs/koa';
import { IMiddleware, Inject } from '@midwayjs/core';
import { MerchantService } from '../service/merchant';

/**
 * 日志中间件
 */
@Middleware()
export class WhiteIpMiddleware implements IMiddleware<Context, NextFunction> {

  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      const ip = ctx.req.headers['x-forwarded-for'] || ctx.req.socket.remoteAddress.replace('::ffff:', '')
      const merchantService = await ctx.requestContext.getAsync(
        MerchantService
      );
      const mchId = ctx.request.body['mchId'];
      let merchant = null;
      if (mchId) {
        merchant = await merchantService.getByMchId(mchId);
      }
      if (!merchant) {
        throw new Error('No Permission')
      }
      if (!merchant.whiteIp.split(',').includes(ip)) {
        throw new Error('IP访问受限')
      }
      await next();
    };
  }
}
