<?php

namespace App\Http\Middleware;

use Closure;
use JWTAuth;
use Exception;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
use Illuminate\Http\Request;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Illuminate\Support\Carbon;

class JwtMiddleware extends BaseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next){
        /*try {
            $user = JWTAuth::parseToken()->authenticate();
        } catch (Exception $e) {
            if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException) {
                return $this->makeResponse(true, "Token inválido", [], 401);
            } else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException) {
                //return response()->json(['status' => 'Token is Expired']);
                return $this->makeResponse(true, "Token expirado", [], 401);
            } else {
                //return response()->json(['status' => 'Authorization Token not found']);
                var_dump($e->getMessage());
                return $this->makeResponse(true, "No se encontró el token de autorización", [], 401);
            }
        }*/

        $auth = $request->header('Authorization');
        if(is_null($auth)){
            return $this->makeResponse(true, "No se encontró el token de autorización", [], 401);
        }else if(!str_contains($auth, "Bearer")){
            return $this->makeResponse(true, "No se encontró el token de autorización", [], 401);
        }

        $token = str_replace("Bearer ", "", $auth);
        $publicKey = "P+UDmQDJgudw9STZpUCyI7XtLmWjhXL4Cy4MRJ8DFsA=";

        $decoded = JWT::decode($token, new Key($publicKey, 'EdDSA'));
        $currentDate = Carbon::now();
        $nowUnix = $currentDate->timestamp;
        
        if($nowUnix > $decoded->cad){
            return response()->json(['status' => 'Token is Expired']);
        }

        return $next($request);
    }

    private function makeResponse($error, $msg, $response = [], $code = 200){
        $respuesta = json_encode([
            "error" => $error,
            "msg" => $msg,
            "response" => $response
        ]);

        return response($respuesta, $code)->header('Content-Type', 'application/json');
    }
}
