<?php

namespace Tests\Unit\Actions;

use App\Actions\CreateRouteAction;
use App\Models\Feed;
use App\Models\Language;
use App\Models\PlatformChannel;
use App\Models\Route;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class CreateRouteActionTest extends TestCase
{
    use RefreshDatabase;

    private CreateRouteAction $action;

    protected function setUp(): void
    {
        parent::setUp();
        $this->action = new CreateRouteAction;
    }

    public function test_creates_route_with_defaults(): void
    {
        $language = Language::factory()->create();
        $feed = Feed::factory()->language($language)->create();
        $channel = PlatformChannel::factory()->create();

        $route = $this->action->execute($feed->id, $channel->id);

        $this->assertInstanceOf(Route::class, $route);
        $this->assertEquals($feed->id, $route->feed_id);
        $this->assertEquals($channel->id, $route->platform_channel_id);
        $this->assertEquals(0, $route->priority);
        $this->assertTrue($route->is_active);
    }

    public function test_creates_route_with_custom_priority(): void
    {
        $language = Language::factory()->create();
        $feed = Feed::factory()->language($language)->create();
        $channel = PlatformChannel::factory()->create();

        $route = $this->action->execute($feed->id, $channel->id, 75);

        $this->assertEquals(75, $route->priority);
        $this->assertTrue($route->is_active);
    }

    public function test_creates_inactive_route(): void
    {
        $language = Language::factory()->create();
        $feed = Feed::factory()->language($language)->create();
        $channel = PlatformChannel::factory()->create();

        $route = $this->action->execute($feed->id, $channel->id, 0, false);

        $this->assertFalse($route->is_active);
    }

    public function test_returns_existing_route_for_duplicate_feed_channel_pair(): void
    {
        $language = Language::factory()->create();
        $feed = Feed::factory()->language($language)->create();
        $channel = PlatformChannel::factory()->create();

        $first = $this->action->execute($feed->id, $channel->id, 10);
        $second = $this->action->execute($feed->id, $channel->id, 99);

        $this->assertEquals($first->id, $second->id);
        $this->assertEquals(10, $second->priority);
        $this->assertDatabaseCount('routes', 1);
    }
}
