<?php

declare(strict_types=1);

namespace Autogedal\FeedMonitor\Model\Fetch;

use Autogedal\FeedMonitor\Model\Problem;

/**
 * Common feed reading: download (timeouts, retries, HTTP code, empty answer) and format validation (CSV / XML).
 */
class FeedReader
{
    public function __construct(
        private readonly FeedFetcher $fetcher
    ) {
    }

    /**
     * @param array<int, mixed> $curlOptions extra CURLOPT_* values (e.g. a user agent)
     */
    public function read(string $url, FeedFormatInterface $format, array $curlOptions = []): FeedResult
    {
        $fetched = $this->fetcher->fetch($url, $curlOptions);
        if (!$fetched->isOk()) {
            return FeedResult::failed($fetched->getProblem() ?? Problem::FETCH, $fetched->getErrorMessage(), $fetched->getAttempts());
        }

        return $this->parse($fetched->getBody(), $format, $fetched->getAttempts());
    }

    /**
     * Validates content already read (e.g. a copy saved on disk).
     */
    public function parse(string $content, FeedFormatInterface $format, int $attempts = 0): FeedResult
    {
        if (trim($content) === '') {
            return FeedResult::failed(Problem::EMPTY, 'Continut gol', $attempts);
        }
        try {
            $parsed = $format->parse($content);
        } catch (InvalidFeedException $e) {
            return FeedResult::failed(Problem::INVALID, $e->getMessage(), $attempts);
        }

        return FeedResult::ok($parsed->getRows(), $parsed->getSkipped(), $attempts);
    }
}
