<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Security;

use App\Administration\Domain\Model\User\Role;

use function in_array;

use Override;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Vote;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;

/**
 * Voter pour les autorisations sur la gestion des élèves.
 *
 * Règles d'accès :
 * - ADMIN, SUPER_ADMIN, SECRETARIAT : accès complet (CRUD)
 * - Autres rôles : pas d'accès
 *
 * @extends Voter<string, null>
 */
final class StudentVoter extends Voter
{
    public const string VIEW = 'STUDENT_VIEW';
    public const string CREATE = 'STUDENT_CREATE';
    public const string MANAGE = 'STUDENT_MANAGE';

    private const array SUPPORTED_ATTRIBUTES = [
        self::VIEW,
        self::CREATE,
        self::MANAGE,
    ];

    #[Override]
    protected function supports(string $attribute, mixed $subject): bool
    {
        return in_array($attribute, self::SUPPORTED_ATTRIBUTES, true) && $subject === null;
    }

    #[Override]
    protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token, ?Vote $vote = null): bool
    {
        $user = $token->getUser();

        if (!$user instanceof SecurityUser) {
            return false;
        }

        return $this->hasAnyRole($user->getRoles(), [
            Role::SUPER_ADMIN->value,
            Role::ADMIN->value,
            Role::SECRETARIAT->value,
        ]);
    }

    /**
     * @param string[] $userRoles
     * @param string[] $allowedRoles
     */
    private function hasAnyRole(array $userRoles, array $allowedRoles): bool
    {
        foreach ($userRoles as $role) {
            if (in_array($role, $allowedRoles, true)) {
                return true;
            }
        }

        return false;
    }
}
