<?php

declare(strict_types=1);

namespace App\Utils;

use Psr\Http\Message\ServerRequestInterface;

class RequestHelper
{
    /**
     * 获取客户端真实 IP
     *
     * 优先级：X-Forwarded-For → X-Real-IP → ServerParams remote_addr
     */
    public static function getClientIp(ServerRequestInterface $request): ?string
    {
        $forwarded_for = $request->getHeaderLine('X-Forwarded-For');
        if ($forwarded_for !== '') {
            $ips = explode(',', $forwarded_for);
            return trim($ips[0]);
        }

        $real_ip = $request->getHeaderLine('X-Real-IP');
        if ($real_ip !== '') {
            return trim($real_ip);
        }

        $server_params = $request->getServerParams();
        return $server_params['remote_addr'] ?? null;
    }
}
