<?php

namespace App\Actions;

use App\Models\Article;

class ValidateArticleAction
{
    public function __construct(
        private FetchArticleDataAction $fetchArticleData,
        private CreateRouteArticlesAction $createRouteArticles,
    ) {}

    public function execute(Article $article): Article
    {
        logger('Validating article for routes: '.$article->id);

        $articleData = $this->fetchArticleData->execute($article);

        $updateData = [];

        if (! empty($articleData)) {
            $updateData['title'] = $articleData['title'] ?? $article->title;
            $updateData['description'] = $articleData['description'] ?? $article->description;
            $updateData['content'] = $articleData['full_article'] ?? null;
            $updateData['image_url'] = ($articleData['thumbnail'] ?? null) ?: $article->image_url;
        }

        if (! isset($articleData['full_article']) || empty($articleData['full_article'])) {
            logger()->warning('Article data missing full_article content', [
                'article_id' => $article->id,
                'url' => $article->url,
            ]);

            $updateData['validated_at'] = now();
            $article->update($updateData);

            return $article->refresh();
        }

        $updateData['validated_at'] = now();
        $article->update($updateData);

        $this->createRouteArticles->execute($article, $articleData['full_article']);

        return $article->refresh();
    }
}
