<?php

declare(strict_types=1);

namespace App\Framework\Http;

use App\Framework\DI\Initializer;
use App\Framework\Http\Parser\HttpRequestParser;

/**
 * Factory for creating HTTP requests
 * Now uses the new parser system instead of direct superglobal access
 */
final readonly class RequestFactory
{
    public function __construct(
        private HttpRequestParser $parser
    ) {
    }

    /**
     * Create a request from PHP globals
     * This is the only place where we access superglobals
     *
     * @return Request
     */
    #[Initializer]
    public function createFromGlobals(): Request
    {
        // Get raw body once
        $rawBody = file_get_contents('php://input') ?: '';

        // Use parser with minimal superglobal access
        return $this->parser->parseFromGlobals($_SERVER, $rawBody);
    }

    /**
     * Create a request from raw components (for testing)
     *
     * @param string $method HTTP method
     * @param string $uri Request URI
     * @param array<string, mixed> $server Server data
     * @param string $body Raw body
     * @return Request
     */
    public function createFromComponents(
        string $method,
        string $uri,
        array $server = [],
        string $body = ''
    ): Request {
        return $this->parser->parseRequest($method, $uri, $server, $body);
    }

    /**
     * Create a request from a raw HTTP string (for testing)
     *
     * @param string $rawHttpRequest Raw HTTP request string
     * @return Request
     */
    public function createFromRawHttp(string $rawHttpRequest): Request
    {
        return $this->parser->parseRawHttpRequest($rawHttpRequest);
    }
}
