<?php

namespace App\Listeners;

use App\Actions\ValidateArticleAction;
use App\Enums\ActivityTypeEnum;
use App\Enums\LogLevelEnum;
use App\Events\ActionPerformed;
use App\Events\ActivityLogged;
use App\Events\NewArticleFetched;
use Exception;
use Illuminate\Contracts\Queue\ShouldQueue;

class ValidateArticleListener implements ShouldQueue
{
    public string $queue = 'default';

    public function __construct(
        private ValidateArticleAction $validateArticle
    ) {}

    public function handle(NewArticleFetched $event): void
    {
        $article = $event->article;

        if (! is_null($article->validated_at)) {
            return;
        }

        // Skip if already has publication (prevents duplicate processing)
        if ($article->articlePublication()->exists()) {
            return;
        }

        try {
            $this->validateArticle->execute($article);

            ActivityLogged::dispatch(
                ActivityTypeEnum::VALIDATE,
                "Validated \"{$article->title}\"",
                [],
                $article,
            );
        } catch (Exception $e) {
            ActionPerformed::dispatch('Article validation failed', LogLevelEnum::ERROR, [
                'article_id' => $article->id,
                'error' => $e->getMessage(),
            ]);

            ActivityLogged::dispatch(
                ActivityTypeEnum::ERROR,
                "Validation failed for \"{$article->title}\"",
                ['error' => $e->getMessage()],
                $article,
            );
        }
    }
}
