<?php

namespace App\Services;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use App\Helpers\Response;

class JwtService
{

    /**
     * It will generate a token with limit date.
     * 
     * @param array $payload
     * @return string
     * 
     * @throws Exception
     */
    public static function generateToken(array $payload): string
    {
        $now = time();

        $payload = array_merge($payload, [
            'iss' => $_ENV['APP_NAME'],
            'iat' => $now,
            'exp' => $now + (int) $_ENV['JWT_TTL']
        ]);
        return JWT::encode($payload, $_ENV['JWT_SECRET'], $_ENV['JWT_HASH']);
    }

    /**
     * It will validate a token.
     * 
     * @param string $token
     * @return object
     * 
     * @throws Exception
     */
    public static function validateToken(string $token): array
    {
        try {
            return (array) JWT::decode(
                $token,
                new Key($_ENV['JWT_SECRET'], $_ENV['JWT_HASH'])
            );
        } catch (\Throwable $e) {
            throw new \Exception('INVALID_TOKEN');
        }
    }
}
