<?php
declare(strict_types=1);

namespace App\Security\Voter;

use App\ApiResources\Cotisation\Cotisation;
use App\Entity\Access\Access;
use App\Service\Network\Utils as NetworkUtils;
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 CotisationVoter extends Voter
{
    public function __construct(
        private Security $security,
        private NetworkUtils $networkUtils)
    { }

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

    /**
     * @param string $attribute
     * @param mixed $subject
     * @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, do not grant access
        if (!$user instanceof UserInterface) {
            return false;
        }

        if($subject->getOrganizationId() !== $user->getOrganization()->getId()){
            return false;
        }

        return $this->security->isGranted('ROLE_COTISATION') &&
            $this->networkUtils->isCMFAndActiveNow($user->getOrganization());
    }


}
