'use strict';

module.exports = options => {
  return async function auth(ctx, next) {
    if (options.is_force > 0) {
      await ctx.helper.verify_token(ctx);
    } else {
      await ctx.helper.verify_token_sample(ctx);
    }

    // 判断header中的type
    const type = ctx.request.header.type;
    ctx.logger.info('course_headers: ' + JSON.stringify(ctx.request.header));

    if (!ctx.isEmpty(type) && type !== 'h5' && type !== 'miniProgram' && !ctx.isEmpty(ctx.userUuid)) {
      const appUserId = ctx.cookies.get('app_user_id', { signed: false });
      const token = ctx.cookies.get('token', { signed: false });
      const userId = ctx.cookies.get('user_id', { signed: false });
      const deviceId = ctx.cookies.get('device_id', { signed: false });
      const deviceLoginId = ctx.cookies.get('device_login_id', { signed: false });

      const params = {
        app_user_id: appUserId,
        token,
        uid: userId,
        device_id: deviceId,
        device_login_id: deviceLoginId,
      };

      const result = await ctx.helper.send_request(ctx.app.config.NODE_URL + '/user/auth', params, {
        method: 'POST',
      });
      ctx.logger.info(JSON.stringify({ url: ctx.app.config.NODE_URL + '/user/auth', request_header: ctx.request.header, user_auth_params: params, user_auth_result: result }));
      if (result.status !== 201 || ctx.isEmpty(result.data)) {
        this.throw(401, 'token已失效');
        return;
      }

      const phone = ctx.isEmpty(result.data.data.passport) ? '' : result.data.data.passport;
      const user = await ctx.classModel.V5.CourseUser.findOne({ where: { uuid: ctx.userUuid, is_deleted: 0 } });
      if (ctx.isEmpty(user) || user.phone !== phone) {
        this.throw(401, 'token校验不一致');
      }
    }

    await next();
  };
};
