<?php

namespace NoahVet\Reef\Infrastructure\Http\Multipart;

use NoahVet\Reef\Domain\Http\Multipart\MultipartParserInterface;
use NoahVet\Reef\Domain\Http\Multipart\MultipartPart;
use Symfony\Component\HttpFoundation\Request;

class RequestMultipartParser implements RequestMultipartParserInterface
{
    public function __construct(
        private readonly MultipartParserInterface $multipartParser,
    ) {
    }

    #[\Override]
    public function parse(Request $request): MultipartPart
    {
        $contentType = $request->headers->get('Content-Type', '');
        $rawBody = $request->getContent();

        $stream = \fopen('php://temp', 'r+');
        if (!\is_resource($stream)) {
            throw new \RuntimeException('Failed to open temporary stream');
        }
        \fwrite($stream, "Content-Type: {$contentType}\r\n\r\n{$rawBody}");

        return $this->multipartParser->parse($stream);
    }
}
