<?php

namespace app\rpc\client;

use Exception;
use Webman\Config;

class AuthRpcClient
{
    protected $client;
    protected $host;
    protected $port;

    /**
     * AuthRpcClient constructor.
     * @param string $host
     * @param int $port
     */
    public function __construct(string $host = '', int $port = 0)
    {
        // 从配置文件中获取 RPC 服务的连接信息
//        $this->host = $host ?: Config::get('rpc.auth_host', '192.168.21.27');
//        $this->port = $port ?: Config::get('rpc.auth_port', 22101);
////        dump($this->host);dump($this->port);
//        // 连接到 Auth RPC 服务
//        $this->client = stream_socket_client("tcp://{$this->host}:{$this->port}", $errorCode, $errorMessage);
//        dump($this->client);
//        if (false === $this->client) {
//            throw new Exception("RPC 连接失败: {$errorMessage}");
//        }
    }

    /**
     * 验证 JWT token
     *
     * @param string $jwtToken
     * @return array
     * @throws Exception
     */
    public function validateJwtToken(string $jwtToken): array
    {
      // 从配置文件中获取 RPC 服务的连接信息
        $host = config('rpc.auth_host', '192.168.21.27');
        $port = config('rpc.auth_port', 22101);
// dump($host);dump($port); return [];
        // 创建连接到 Auth RPC 服务
        $client = stream_socket_client("tcp://{$host}:{$port}", $errorCode, $errorMessage);

        if (false === $client) {
            throw new Exception("RPC 连接失败: {$errorMessage}");
        }

        $rpcRequest = [
            'class'  => 'Auth',
            'method' => 'ValidateJwtToken',
            'args'   => [
                ['jwt_token' => $jwtToken],
            ],
        ];
//        dump($rpcRequest);return [];

        // 发送请求,Text 协议需要在末尾添加换行符
        fwrite($this->client, json_encode($rpcRequest) . "\n");

        // 读取响应
        $result = fgets($this->client, 10240000);
        if (!$result) {
            throw new Exception('没有收到来自 Auth RPC 服务的响应');
        }

        // 解码 JSON 响应
        $response = json_decode($result, true);

        return $response;
    }

    /**
     * 关闭与 RPC 服务的连接
     */
    public function close()
    {
        if ($this->client) {
            fclose($this->client);
        }
    }
}