<?php

namespace App\Actions;

use App\Models\Article;
use App\Services\Factories\ArticleParserFactory;
use App\Services\Http\HttpFetcher;
use App\Services\Log\LogSaver;
use Exception;

class FetchArticleDataAction
{
    public function __construct(
        private LogSaver $logSaver
    ) {}

    /**
     * @return array<string, mixed>
     */
    public function execute(Article $article): array
    {
        try {
            $html = HttpFetcher::fetchHtml($article->url);
            $parser = ArticleParserFactory::getParser($article->url);

            return $parser->extractData($html);
        } catch (Exception $e) {
            $this->logSaver->error('Exception while fetching article data', null, [
                'url' => $article->url,
                'error' => $e->getMessage(),
            ]);

            return [];
        }
    }
}
