<?php

namespace App\Listeners;

use App\Actions\PublishRouteArticleAction;
use App\Events\RouteArticleApproved;
use Exception;
use Illuminate\Contracts\Queue\ShouldQueue;

class PublishApprovedArticleListener implements ShouldQueue
{
    public string $queue = 'publishing';

    public function __construct(
        private PublishRouteArticleAction $publishRouteArticle,
    ) {}

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

        if ($article->articlePublications()
            ->where('platform_channel_id', $routeArticle->platform_channel_id)
            ->exists()
        ) {
            return;
        }

        try {
            $this->publishRouteArticle->execute($routeArticle);
        } catch (Exception) {
            // The action has already recorded the failure and notified.
        }
    }
}
