<?php
declare(strict_types=1);

namespace App\Security\Voter;

use App\Entity\Access\Access;
use App\Service\Security\SwitchUser;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\User\UserInterface;

class SwitchUserVoter extends Voter
{
    public function __construct(private Security $security, private SwitchUser $switchUser)
    { }

    protected function supports(string $attribute, $subject): bool
    {
        return in_array($attribute, ['CAN_SWITCH_USER'])
            && $subject instanceof UserInterface;
    }

    /**
     * @param string $attribute
     * @param mixed $subject User to switch
     * @param TokenInterface $token
     * @return bool
     */
    protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
    {
        /** @var Access $user */
        $user = $token->getUser();

        // if the user is anonymous or if the subject is not a user, do not grant access
        if (!$user instanceof UserInterface || !$subject instanceof UserInterface) {
            return false;
        }

        // check for ROLE_ALLOWED_TO_SWITCH
        if ($this->security->isGranted('ROLE_ALLOWED_TO_SWITCH')) {
            return true;
        }

        if ($this->switchUser->isAllowedToSwitch($user, $subject)) {
            return true;
        }

        return true;
    }
}