<?php

declare(strict_types=1);

namespace Autogedal\FeedMonitor\Model\Fetch;

/**
 * One HTTP GET with curl (kept apart from FeedFetcher so the retry logic can be tested without network).
 */
class HttpClient
{
    /**
     * @param array<int, mixed> $curlOptions extra CURLOPT_* values
     * @return array{body: string|false, http_code: int, error: string, errno: int}
     */
    public function get(string $url, int $connectTimeout, int $timeout, array $curlOptions = []): array
    {
        $ch = curl_init();
        curl_setopt_array($ch, $curlOptions + [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS => 5,
            CURLOPT_CONNECTTIMEOUT => $connectTimeout,
            CURLOPT_TIMEOUT => $timeout,
        ]);
        $body = curl_exec($ch);
        $result = [
            'body' => $body,
            'http_code' => (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE),
            'error' => curl_error($ch),
            'errno' => curl_errno($ch),
        ];
        curl_close($ch);

        return $result;
    }

    public function sleep(int $seconds): void
    {
        if ($seconds > 0) {
            sleep($seconds);
        }
    }
}
