<?php

namespace App\Actions;

use App\Models\Article;
use App\Models\Route;

class BackfillRouteArticlesAction
{
    public function __construct(
        private CreateRouteArticlesAction $createRouteArticles,
    ) {}

    public function execute(Route $route): void
    {
        if (! $route->is_active) {
            return;
        }

        // Articles already validated with content, but never routed to this
        // route. Uses the stored content rather than re-fetching, so a large
        // backlog cannot trigger a network storm (#157).
        Article::query()
            ->where('feed_id', $route->feed_id)
            ->whereNotNull('content')
            ->whereDoesntHave('routeArticles', function ($query) use ($route) {
                $query->where('feed_id', $route->feed_id)
                    ->where('platform_channel_id', $route->platform_channel_id);
            })
            ->lazy()
            ->each(function (Article $article) use ($route) {
                $this->createRouteArticles->createForRoute($article, $route, (string) $article->content);
            });
    }
}
