<?php

namespace App\Actions;

use App\Models\Article;
use App\Models\Feed;
use App\Services\Http\HttpFetcher;
use App\Services\Log\LogSaver;
use Exception;
use Illuminate\Support\Collection;

class FetchRssArticlesAction
{
    public function __construct(
        private LogSaver $logSaver,
        private SaveArticleAction $saveArticle,
    ) {}

    /**
     * @return Collection<int, Article>
     */
    public function execute(Feed $feed): Collection
    {
        try {
            $xml = HttpFetcher::fetchHtml($feed->url);

            $previousUseErrors = libxml_use_internal_errors(true);

            try {
                $rss = simplexml_load_string($xml);
            } finally {
                libxml_clear_errors();
                libxml_use_internal_errors($previousUseErrors);
            }

            if ($rss === false || ! isset($rss->channel->item)) {
                $this->logSaver->warning('Failed to parse RSS feed XML', null, [
                    'feed_id' => $feed->id,
                    'feed_url' => $feed->url,
                ]);

                return collect();
            }

            $articles = collect();
            foreach ($rss->channel->item as $item) {
                $link = (string) $item->link;
                if ($link !== '') {
                    $articles->push($this->saveArticle->execute($link, $feed->id));
                }
            }

            return $articles;
        } catch (Exception $e) {
            $this->logSaver->error('Failed to fetch articles from RSS feed', null, [
                'feed_id' => $feed->id,
                'feed_url' => $feed->url,
                'error' => $e->getMessage(),
            ]);

            return collect();
        }
    }
}
