<?php

declare(strict_types=1);

namespace App\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class RpcLoggerMiddleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        var_dump($request, '---------------1----');
        var_dump($request->getRequestTarget(), '-------------2----');
        // 记录请求信息
        $data = $request->getParsedBody();
        $logger = \Hyperf\Utils\ApplicationContext::getContainer()
            ->get(\Hyperf\Logger\LoggerFactory::class)
            ->get('rpc');

        $logger->info('RPC请求', [
            'method' => $data['method'] ?? 'unknown',
            'params' => $data['params'] ?? [],
            'timestamp' => microtime(true)
        ]);

        // 处理请求
        $response = $handler->handle($request);

        // 记录响应信息
        $logger->info('RPC响应', [
            'method' => $data['method'] ?? 'unknown',
            'response' => $response->getBody()->getContents(),
            'timestamp' => microtime(true)
        ]);

        return $response;
    }
}
