<?php

namespace App\Http\Middleware;

use Closure;
use JWTAuth;
use Exception;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;

class JWTMiddleware extends BaseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        try {
            $user = JWTAuth::parseToken()->authenticate();
        }catch (\Tymon\JWTAuth\Exceptions\JWTException $e) {
            return response()->json(['error' =>"Tidak ada Token"],400);
        } catch (Exception $exception) {
            if ($exception instanceof TokenExpiredException) {
                try {
                    $refreshed = JWTAuth::refresh(JWTAuth::getToken());
                    $user = JWTAuth::setToken($refreshed)->toUser();
                    $request->headers->set('Authorization', 'Bearer ' . $refreshed);
                } catch (\JWTException $e) {
                    return response()->json([
                        'code'   => 103,
                        'message' => 'Token cannot be refreshed, please Login again'
                    ]);
                }
            } else if ($exception instanceof TokenInvalidException) {
                return response()->json(['status' => 'Token is Invalid']);
            } else if ($exception instanceof UnauthorizedHttpException || $exception instanceof TokenBlacklistedException) {
                return response()->json(['status' => 'The token has been blacklisted']);
            }
        }
        return $next($request);
    }
}
