<?php


namespace App\Services;

use App\Entities\Usuario\Usuario;
use App\Services\JWT\JWTPayload\JWTPayload;
//use Cassandra\Varint;
use Config\Services;
use Exception;
use Firebase\JWT\JWT;

class JWTService {

	public function validateJWTFromRequest($authenticationHeader, ?array $route): bool {

		$encodedToken = is_null( $authenticationHeader ) ? false : explode( ' ', $authenticationHeader ) [1];
		if (!$encodedToken) return false;
		try {
			$key = Services::getSecretKey();
			$decodedToken = JWT::decode( $encodedToken, $key, [ 
					'HS256'
			] );
			$userHasPermission = in_array( $route ['endpoint_id'], $decodedToken->permissions );
			$routeIsNotRestrict = $route ['restrict'] === false;
			return $userHasPermission || $routeIsNotRestrict;
		} catch ( Exception $exception ) {
			return false;
		}

	}

	public static function getTokenJWTPayload(): ?JWTPayload {

		$http_auth_header = $_SERVER ['HTTP_AUTHORIZATION'];
		if ($http_auth_header) {
			$encoded_token = str_replace( 'Bearer ', '', $http_auth_header );
			$key = Services::getSecretKey();
			$decoded_token = JWT::decode( $encoded_token, $key, [ 
					'HS256'
			] );
			return JWTPayload::builder()->setUid( $decoded_token->uid )
				->setProfile( $decoded_token->profile )
				->setExp( $decoded_token->exp )
				->setIat( $decoded_token->iat )
				->setPermissions( $decoded_token->permissions )
				->build();
		} else {
			return null;
		}

	}

	public function getSignedJWTForUser(Usuario $usuario, $profile): string {

		$issuedAtTime = time();
		$tokenTimeToLive = getenv( 'JWT_TIME_TO_LIVE' );
		$tokenExpiration = $issuedAtTime + $tokenTimeToLive;
		$payload = JWTPayload::builder()->setUid( $usuario->getId() )
			->setIat( $issuedAtTime )
			->setExp( $tokenExpiration )
			->setProfile( $profile )
			->setPermissions( $usuario->getPermissoes() )
			->build()
			->toArray();
		return JWT::encode( $payload, Services::getSecretKey() );

	}

}
