<?php
declare(strict_types=1);

namespace App\Security\Voter;

use App\Entity\Access\Access;
use App\Entity\Core\ContactPoint;
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 ContactPointVoter extends Voter
{
    public function __construct(private Security $security)
    { }

    protected function supports(string $attribute, $subject): bool
    {
        return in_array($attribute, ['CONTACT_POINT_READ', 'CONTACT_POINT_EDIT', 'CONTACT_POINT_DELETE'])
            && $subject instanceof ContactPoint;
    }

    /**
     * @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;
        }
        switch ($attribute) {
            case 'CONTACT_POINT_READ':
                if($subject->getOrganization()->count() === 1){
                    return $this->security->isGranted('ROLE_ORGANIZATION_VIEW')
                        && $subject->getOrganization()->current()->getId() === $user->getOrganization()->getId();
                }
                break;
            case 'CONTACT_POINT_EDIT':
            case 'CONTACT_POINT_DELETE':
                if($subject->getOrganization()->count() === 1){
                    return $this->security->isGranted('ROLE_ORGANIZATION')
                        && $subject->getOrganization()->current()->getId() === $user->getOrganization()->getId();
                }
                break;
        }

        return false;
    }


}
