<?php

namespace App\Actions;

use App\Events\RouteActivated;
use App\Models\Route;

class CreateRouteAction
{
    /**
     * Create a route or return an existing one for the same feed+channel pair.
     * When a route already exists, the provided priority and isActive values are ignored.
     */
    public function execute(int $feedId, int $platformChannelId, int $priority = 0, bool $isActive = true): Route
    {
        $route = Route::firstOrCreate(
            [
                'feed_id' => $feedId,
                'platform_channel_id' => $platformChannelId,
            ],
            [
                'priority' => $priority,
                'is_active' => $isActive,
            ]
        );

        if ($route->wasRecentlyCreated && $route->is_active) {
            RouteActivated::dispatch($route->feed_id, $route->platform_channel_id);
        }

        return $route;
    }
}
