<?php

namespace App\Http\Middleware;

use App\Modules\Push\Services\PushService;
use App\Modules\User\Services\QappUserService;
use App\Modules\User\Services\UserService;
use Closure;
use Exception;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Middleware\BaseMiddleware;

class QuickAppGetUserFromToken extends BaseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $version = $request->header('X-Version', '');
        if (!$token = $this->auth->setRequest($request)->getToken()) {
            return response()->error('QAPP_NOT_LOGIN');
        }
        try {
            $user          = $this->auth->authenticate($token);
            $send_order_id = $request->header('send-order-id', 0);
            if ($send_order_id) {
                UserService::setUserSendOrder($user->id, $send_order_id);
            }
            (new QappUserService)->setGolableUser($user->id);
        } catch (TokenExpiredException $e) {
            return response()->error('QAPP_TOKEN_ERROR');
        } catch (JWTException $e) {
            return response()->error('QAPP_TOKEN_ERROR');
        } catch (Exception $e) {
            myLog('QuickAppGetUserFromToken')->info($e->getMessage());
            return response()->error('QAPP_NOT_LOGIN');
        }

        // 更新用户reg_id
        $uid      = $user->id;
        $package  = $request->header('x-package', '');
        $provider = $request->header('x-provider', '');
        $regId    = $request->header('x-regid', '');
        PushService::setUserRegId($uid, $regId, $provider, $package);

        return $next($request);
    }
}
