<?php

declare(strict_types=1);

namespace App\Framework\HttpClient;

use App\Framework\Http\Headers;
use App\Framework\Http\Status;
use CurlHandle;

final readonly class CurlResponseParser
{
    public function parse(string $rawResponse, CurlHandle $curlHandle): ClientResponse
    {
        $headerSize = curl_getinfo($curlHandle, CURLINFO_HEADER_SIZE);
        $headersRaw = substr($rawResponse, 0, $headerSize);
        $body = substr($rawResponse, $headerSize);
        $statusCode = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);

        $headers = $this->parseHeaders($headersRaw);
        $status = Status::from($statusCode);

        return new ClientResponse($status, $headers, $body);
    }

    private function parseHeaders(string $headersRaw): Headers
    {
        $headers = new Headers();
        $lines = explode("\r\n", trim($headersRaw));

        foreach ($lines as $line) {
            if (str_contains($line, ':')) {
                [$name, $value] = explode(':', $line, 2);
                $headers = $headers->with(trim($name), trim($value));
            }
        }

        return $headers;
    }
}
