<?php

namespace App\Actions;

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

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

    /**
     * @return Collection<int, Article>
     */
    public function execute(Feed $feed): Collection
    {
        try {
            $parser = HomepageParserFactory::getParserForFeed($feed);

            if (! $parser) {
                $this->logSaver->warning('No parser available for feed URL', null, [
                    'feed_id' => $feed->id,
                    'feed_url' => $feed->url,
                ]);

                return collect();
            }

            $html = HttpFetcher::fetchHtml($feed->url);
            $urls = $parser->extractArticleUrls($html);

            return collect($urls)
                ->map(fn (string $url) => $this->saveArticle->execute($url, $feed->id));

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

            return collect();
        }
    }
}
