<?php

declare(strict_types=1);

namespace Autogedal\FeedMonitor\Model\Fetch;

/**
 * Test double used only by `bin/magento autogedal:feed-monitor:run --feed-file / --http-code / --connection-error`:
 * the command makes it the HttpClient of its own process, so a job can be run against a broken feed. Never configured
 * for the cron.
 */
class SimulatedHttpClient extends HttpClient
{
    /** @var array{body: string|false, http_code: int, error: string, errno: int}|null */
    private ?array $response = null;
    private string $urlPart = '';
    private int $simulatedRequests = 0;

    /**
     * @param string|null $body content, null for a host that does not answer
     * @param string $urlPart only requests whose URL contains it are simulated (one sub-feed)
     */
    public function setResponse(?string $body, int $httpCode = 200, string $urlPart = ''): void
    {
        $this->response = $body === null
            ? ['body' => false, 'http_code' => 0, 'error' => 'Failed to connect: Connection timed out (simulat)', 'errno' => 28]
            : ['body' => $body, 'http_code' => $httpCode, 'error' => '', 'errno' => 0];
        $this->urlPart = $urlPart;
    }

    public function get(string $url, int $connectTimeout, int $timeout, array $curlOptions = []): array
    {
        if ($this->response !== null && ($this->urlPart === '' || str_contains($url, $this->urlPart))) {
            $this->simulatedRequests++;
            return $this->response;
        }

        return parent::get($url, $connectTimeout, $timeout, $curlOptions);
    }

    public function sleep(int $seconds): void
    {
        // no waiting between simulated attempts
    }

    /**
     * Lets the command tell whether the simulation was really used by the job.
     */
    public function getSimulatedRequests(): int
    {
        return $this->simulatedRequests;
    }
}
