<?php

namespace App\Framework\HttpClient;

use App\Framework\Http\HeaderManipulator;

final readonly class CurlRequestBuilder
{
    public function buildOptions(ClientRequest $request): array
    {
        $url = $request->url;
        if (!empty($request->options->query)) {
            $separator = str_contains($url, '?') ? '&' : '?';
            $url .= $separator . http_build_query($request->options->query);
        }

        $options = [
            CURLOPT_URL => $url,
            CURLOPT_CUSTOMREQUEST => $request->method->value,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => true,
            CURLOPT_TIMEOUT => $request->options->timeout,
            CURLOPT_CONNECTTIMEOUT => $request->options->connectTimeout,
            CURLOPT_FOLLOWLOCATION => $request->options->followRedirects,
            CURLOPT_MAXREDIRS => $request->options->maxRedirects,
            CURLOPT_SSL_VERIFYPEER => $request->options->verifySsl,
            CURLOPT_SSL_VERIFYHOST => $request->options->verifySsl ? 2 : 0,
        ];

        if ($request->options->userAgent !== null) {
            $options[CURLOPT_USERAGENT] = $request->options->userAgent;
        }

        if ($request->options->proxy !== null) {
            $options[CURLOPT_PROXY] = $request->options->proxy;
        }

        if ($request->body !== '') {
            $options[CURLOPT_POSTFIELDS] = $request->body;
        }

        if (count($request->headers->all()) > 0) {
            $options[CURLOPT_HTTPHEADER] = HeaderManipulator::formatForCurl($request->headers);
        }

        return $options;
    }
}
