<?php

namespace App\Utils;

use App\Constants\HttpEnumCode;
use App\Exception\BusinessException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\Key;
use Firebase\JWT\SignatureInvalidException;

class Jwt
{
    /**
     * 生成jwttoken
     * @param array $data 自定义数组
     */
    public function encode(array $data): string
    {
        $time = time();
        $secret = config('jwt.secret');
        $expire = config('jwt.ttl');
        $algo = config('jwt.algo');
        $payload = [
            'iss' => 'gdxz',
            'iat' => $time,
            'nbf' => $time,
            'exp' => $time + $expire,
            'userInfo' => $data,
        ];
        //        token_type:bearer
        return \Firebase\JWT\JWT::encode($payload, $secret, $algo);
    }

    /**
     * 解码jwttoken
     * @param string $token token数据，不卸载bearer
     * @return array
     */
    public function decode(string $token): array
    {
        $secret = config('jwt.secret');
        try {
            $jwt = json_decode(json_encode(\Firebase\JWT\JWT::decode($token, new Key($secret, 'HS256'))), true); // 解密jwt

        } catch (SignatureInvalidException $e) {
            // 签名不正确
            throw new BusinessException( $e->getMessage(),HttpEnumCode::TOKEN_ERROR);

        } catch (ExpiredException|\UnexpectedValueException|\InvalidArgumentException $e) {
            // token过期
            throw new BusinessException( $e->getMessage(),HttpEnumCode::TOKEN_EXPTIRED);

        } catch (\Throwable $e) {
            // 其他错误:
            throw new BusinessException( $e->getMessage());
        }

        return $jwt;
    }
}