<?php

namespace App\Security\Voter;

use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;

/**
 * Gestion des utilisateurs : valider/refuser une demande, gérer les comptes.
 * - USER_VALIDATE     : ADMIN ou AUDIT (ADMIN hérite d'AUDIT via la hiérarchie).
 * - USER_MANAGE_ADMIN : promouvoir/rétrograder un ADMIN, réservé aux ADMIN.
 *
 * @extends Voter<string, User|null>
 */
final class UserManagementVoter extends Voter
{
    public const VALIDATE = 'USER_VALIDATE';
    public const MANAGE_ADMIN = 'USER_MANAGE_ADMIN';

    public function __construct(
        private readonly RoleHierarchyInterface $roleHierarchy,
    ) {
    }

    protected function supports(string $attribute, mixed $subject): bool
    {
        return \in_array($attribute, [self::VALIDATE, self::MANAGE_ADMIN], true);
    }

    protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
    {
        $user = $token->getUser();
        if (!$user instanceof User || !$user->isActive()) {
            return false;
        }

        $reachable = $this->roleHierarchy->getReachableRoleNames($user->getRoles());

        return match ($attribute) {
            self::VALIDATE => \in_array(User::ROLE_AUDIT, $reachable, true),
            self::MANAGE_ADMIN => \in_array(User::ROLE_ADMIN, $reachable, true),
            default => false,
        };
    }
}
