<?php

declare(strict_types=1);

namespace app\common\library\admin;

use Webman\Http\Request;

final class WebSocketConfigHelper
{
    public static function wsUrl(?Request $request = null): string
    {
        $url = trim((string) env('H5_WEBSOCKET_URL', ''));
        if ($url !== '') {
            return $url;
        }

        if ($request !== null) {
            $proto = strtolower((string) $request->header('x-forwarded-proto', ''));
            if ($proto === '') {
                $proto = strtolower((string) $request->header('x-forwarded-protocol', ''));
            }
            $isHttps = $proto === 'https'
                || strtolower((string) $request->header('x-forwarded-ssl', '')) === 'on'
                || strtolower((string) $request->header('x-scheme', '')) === 'https';
            $scheme = $isHttps ? 'wss' : 'ws';

            $host = trim((string) $request->header('host', ''));
            if ($host === '') {
                $host = trim((string) $request->header('x-forwarded-host', ''));
            }
            if ($host !== '') {
                return $scheme . '://' . $host . '/ws/';
            }
        }

        return 'ws://127.0.0.1:3131/ws/';
    }
}

