<?php

namespace App\Http\Middleware;

use Closure;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Http\Request;
use JWTAuth;

class RefreshJwtToken extends \Tymon\JWTAuth\Http\Middleware\BaseMiddleware
{


    public function handle($request, Closure $next)
    {
        //If not logged or no token is present, simply let it pass
        if (!$this->checkForToken($request)) {
            return $next($request);
        }

        //check if the token is ending soon
        if (!$this->endingSoon()) {
            //not ending soon, the response will contain the same token
            $token = $this->auth->parser()->setRequest($request)->parseToken();
        } else {
            try {
                $token = $this->auth->parseToken()->refresh();
            } catch (JWTException $e) {
                return $next($request);
            }
        }

        $response = $next($request);

        // Send the token back to the client.
        return $this->setAuthenticationHeader($response, $token);
    }

    public function checkForToken(Request $request)
    {
        return $this->auth->parser()->setRequest($request)->hasToken();
    }

    /**
     * Checks if a token is ending soon
     */
    private function endingSoon(): bool
    {
        $expiration = (JWTAuth::parseToken()->getClaim('exp'));

        $diff =  $expiration - time();
        if ($diff / 60 <= intval(env('JWT_TTL_RENEW_TOLERANCE', 5))) {
            return true;
        }

        return false;
    }
}
