<?php

namespace App\Security\Voter;

use App\Entity\User;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;

/**
 * Accorde ROLE_ADMIN aux utilisateurs dont l'email figure dans ADMIN_EMAILS.
 * Permet de réserver le menu Paramètres sans stocker le rôle en base.
 *
 * @extends Voter<string, mixed>
 */
final class AdminVoter extends Voter
{
    /** @var list<string> */
    private array $adminEmails;

    public function __construct(
        #[Autowire('%env(ADMIN_EMAILS)%')]
        string $adminEmails,
    ) {
        $this->adminEmails = array_values(array_filter(array_map(
            static fn (string $e) => strtolower(trim($e)),
            explode(',', $adminEmails)
        )));
    }

    protected function supports(string $attribute, mixed $subject): bool
    {
        return 'ROLE_ADMIN' === $attribute;
    }

    protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
    {
        $user = $token->getUser();

        return $user instanceof User
            && in_array(strtolower($user->getUserIdentifier()), $this->adminEmails, true);
    }
}
