<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Security\Authorization;

use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Entity\UserGroup;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;

final class UserGroupVoter extends Voter
{
    public const APPEND_TO_GROUP = 'CHILL_MAIN_USER_GROUP_APPEND_TO_GROUP';

    public function __construct(private readonly Security $security) {}

    protected function supports(string $attribute, $subject)
    {
        return self::APPEND_TO_GROUP === $attribute && $subject instanceof UserGroup;
    }

    protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token)
    {
        /* @var UserGroup $subject */
        if ($this->security->isGranted('ROLE_ADMIN')) {
            return true;
        }

        $user = $this->security->getUser();

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

        return $subject->getAdminUsers()->contains($user);
    }
}
