<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

use App\Http\Controllers\ResponseController;
use Exception;

class JWTMiddleware{
    private $responseController;
    private $publicKey = "zOgD0uF22+xg37nTmA+bg/6/E80BJYeHeByGpeTrNFw=";
    /**
     * 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 __construct(){
        $this->responseController = new ResponseController();
    }

    public function handle(Request $request, Closure $next){
        $token = $request->bearerToken();
        if(is_null($token)){
            return $this->responseController->makeResponse(true, "No se encontró el token de autorización.", [], 401);
        }

        try{
            $decoded = JWT::decode($token, new Key($this->publicKey, 'EdDSA'));
        }catch(Exception $e){
            return $this->responseController->makeResponse(true, "Token inválido.", [], 401);
        }

        $usr = DB::table('S002V01TUSUA')->where('USUA_COEL', '=', $decoded->iss)->first();
        if(is_null($usr)){
            return $this->responseController->makeResponse(true, "El usuario que generó el token no está registrado en la base.", [], 401);
        }else if($usr->USUA_ESTA == 'Inactivo'){
            return $this->responseController->makeResponse(true, "El usuario que generó el token está desactivado.", [], 401);
        }else if($usr->USUA_ESTA == 'Eliminado'){
            return $this->responseController->makeResponse(true, "El usuario que generó el token está eliminado.", [], 401);
        }

        if($decoded->aud != "dominio.syp.mx"){
            return $this->responseController->makeResponse(true, "El token no fue generado en este sistema.", [], 401);
        }

        $now = Carbon::now('America/Mexico_city')->timestamp;
        if($now > $decoded->cad){
            return $this->responseController->makeResponse(true, "Token expirado.", [], 401);
        }
        
        return $next($request);
    }
}
