<?php

declare(strict_types=1);

namespace App\Tests\Functional\Module\Core;

use App\Module\Core\Application\Rbac\RbacSeeder;
use App\Module\Core\Domain\Entity\User;
use App\Module\Core\Domain\Security\SystemRoles;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

use function array_map;
use function uniqid;

/**
 * @internal
 */
final class UserDefaultRoleListenerTest extends KernelTestCase
{
    public function testNewUserReceivesDefaultUserRole(): void
    {
        $kernel = self::bootKernel();
        $em     = self::getContainer()->get(EntityManagerInterface::class);
        self::getContainer()->get(RbacSeeder::class)->ensureSystemRoles();

        $user = new User();
        $user->setUsername('listener-'.uniqid());
        $user->setPassword('x');
        $em->persist($user);
        $em->flush();
        $id = $user->getId();

        $em->clear();
        $reloaded = $em->getRepository(User::class)->find($id);
        self::assertInstanceOf(User::class, $reloaded);

        $codes = array_map(static fn ($role) => $role->getCode(), $reloaded->getRbacRoles()->toArray());
        self::assertContains(
            SystemRoles::USER_CODE,
            $codes,
            'Un utilisateur fraîchement créé doit être rattaché au rôle RBAC de base « user ».',
        );
    }
}
