map $http_upgrade $proxy_connection {
    default "rpc_backend${RPC_PATH}";
    websocket "ws_backend${WS_PATH}";
}

 map $http_upgrade $connection_header {
    default keep-alive;
    websocket upgrade;
}

map $http_upgrade $is_websocket {
    default 0;
    websocket 1;
}

map $status $log_only_errors {
    ~^2 0;      # Don't log any 2xx responses
    default 1;  # Log all other responses
}

log_format minimal '$remote_addr - $status $request_time';

server {
    listen 80;
    server_name _;

    location / {
        proxy_pass http://$proxy_connection;
        resolver 127.0.0.11 ipv6=off valid=10s;
        proxy_http_version 1.1;         # Override default HTTP/1.0
        proxy_set_header Host localhost;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
	    proxy_set_header Upgrade $http_upgrade;  # Forward Upgrade header
        proxy_set_header Connection $connection_header;
        
        proxy_next_upstream error timeout http_502 http_503 http_504;
        proxy_next_upstream_tries 5;     # Retry up to 5 times

        # Keep buffering enabled but prevent disk writes
        proxy_buffering on;
        proxy_buffers 8 16k;
        proxy_buffer_size 16k;
        proxy_max_temp_file_size 0;  # Prevent writing to disk
        proxy_busy_buffers_size 32k;
      
        access_log /dev/stdout minimal if=$log_only_errors;
        error_log /dev/stdout error;

        proxy_connect_timeout 300s;
        proxy_read_timeout 3600s;
        proxy_send_timeout 3600s;
    }
}

upstream rpc_backend {
    server ${PROXY_HOST}:${RPC_PORT};
    keepalive 16;
}

upstream ws_backend {
    server ${PROXY_HOST}:${WS_PORT};
}