<?php

namespace Tests\Feature;

use App\Master\Models\ApiUser;
use App\Master\Models\ApiUserRoute;
use Database\Seeders\Global\ApiUserRouteSeeder;
use Tests\DatabaseTestCase;

class ApiUserRouteSeederTest extends DatabaseTestCase
{
    public function testSeedsAllRoutesForAllApiUsers(): void
    {
        $userA = ApiUser::factory()->create();
        $userB = ApiUser::factory()->create();

        $seeder = new ApiUserRouteSeeder();
        $seeder->run();

        $expectedRoutes = $seeder->getApiAuthenticatedRouteNames();

        $this->assertGreaterThan(0, $expectedRoutes->count(), 'There should be at least one API authenticated route');

        foreach ([$userA, $userB] as $user) {
            $allowedRoutes = ApiUserRoute::where('api_user_id', $user->id)
                ->pluck('route_name')
                ->sort()
                ->values();

            $this->assertEquals(
                $expectedRoutes->sort()->values()->all(),
                $allowedRoutes->all(),
                "API user {$user->name} should have all API authenticated routes"
            );
        }
    }

    public function testIsIdempotent(): void
    {
        $user = ApiUser::factory()->create();

        $seeder = new ApiUserRouteSeeder();
        $seeder->run();
        $countAfterFirst = ApiUserRoute::where('api_user_id', $user->id)->count();

        $seeder->run();
        $countAfterSecond = ApiUserRoute::where('api_user_id', $user->id)->count();

        $this->assertEquals($countAfterFirst, $countAfterSecond, 'Running seeder twice should not create duplicates');
    }

    public function testDoesNothingWhenNoApiUsersExist(): void
    {
        $this->assertCount(0, ApiUser::all());

        $seeder = new ApiUserRouteSeeder();
        $seeder->run();

        $this->assertCount(0, ApiUserRoute::all());
    }
}
