<?php

namespace App\Actions;

use App\Models\Article;
use App\Services\Log\LogSaver;
use Exception;

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

    public function execute(string $url, ?int $feedId = null): Article
    {
        try {
            $article = Article::firstOrCreate(
                ['url' => $url],
                [
                    'feed_id' => $feedId,
                    'title' => $this->generateFallbackTitle($url),
                ]
            );

            if ($article->wasRecentlyCreated) {
                $article->dispatchFetchedEvent();
            }

            return $article;
        } catch (Exception $e) {
            $this->logSaver->error('Failed to create article', null, [
                'url' => $url,
                'feed_id' => $feedId,
                'error' => $e->getMessage(),
            ]);
            throw $e;
        }
    }

    private function generateFallbackTitle(string $url): string
    {
        $path = parse_url($url, PHP_URL_PATH);
        $filename = basename($path ?: $url);

        $title = preg_replace('/\.[^.]*$/', '', $filename);
        $title = str_replace(['-', '_'], ' ', $title);
        $title = ucwords($title);

        return $title ?: 'Untitled Article';
    }
}
