<?php

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Tests\Security;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Security\AdminUserChecker;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAccountStatusException;
use Symfony\Component\Security\Core\Role\RoleHierarchy;
use Symfony\Component\Security\Core\User\InMemoryUser;

final class AdminUserCheckerTest extends TestCase
{
    /**
     * @param list<string> $roles
     */
    #[DataProvider('administratorRolesProvider')]
    public function testAcceptsAdministrators(array $roles): void
    {
        $checker = $this->createChecker();

        $checker->checkPostAuth(new InMemoryUser('admin@example.com', null, $roles));

        self::addToAssertionCount(1);
    }

    /**
     * @return iterable<string, array{list<string>}>
     */
    public static function administratorRolesProvider(): iterable
    {
        yield 'administrateur direct' => [['ROLE_ADMIN']];
        yield 'super administrateur héritant du rôle administrateur' => [['ROLE_SUPER_ADMIN']];
    }

    public function testRejectsNonAdministrator(): void
    {
        $checker = $this->createChecker();

        $this->expectException(CustomUserMessageAccountStatusException::class);
        $this->expectExceptionMessage('Invalid credentials.');

        $checker->checkPostAuth(new InMemoryUser('user@example.com', null, ['ROLE_USER']));
    }

    private function createChecker(): AdminUserChecker
    {
        return new AdminUserChecker(new RoleHierarchy([
            'ROLE_SUPER_ADMIN' => ['ROLE_ADMIN'],
        ]));
    }
}
