<?php

namespace app\util;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\SignatureInvalidException;
use support\exception\BusinessException;

class JwtUtil
{
    /**
     * 生成 JWT Token
     * @param int|string $userId
     * @return string
     */
    public static function generateToken($userId): string
    {
        $config = config('jwt');
        $payload = [
            'iss' => 'webman',          // 签发者
            'aud' => 'client',           // 接收方
            'iat' => time(),            // 签发时间
            'exp' => time() + $config['expire'], // 过期时间
            'sub' => $userId            // 用户标识
        ];
        return JWT::encode($payload, $config['secret'], $config['algorithm']);
    }

    /**
     * 验证并解析 Token
     * @param string $token
     * @return object
     * @throws BusinessException
     */
    public static function verifyToken(string $token)
    {
        $config = config('jwt');
        try {
            return JWT::decode($token, new Key($config['secret'], $config['algorithm']));
        } catch (ExpiredException $e) {
            throw new BusinessException('Token 已过期', 401);
        } catch (SignatureInvalidException $e) {
            throw new BusinessException('Token 无效', 401);
        } catch (\Exception $e) {
            throw new BusinessException('鉴权失败', 401);
        }
    }
}