<?php
declare(strict_types=1);

namespace App\Security\Voter;

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

    protected function supports(string $attribute, $subject): bool
    {
        return in_array($attribute, ['BANK_ACCOUNT_READ', 'BANK_ACCOUNT_EDIT', 'BANK_ACCOUNT_DELETE'])
            && $subject instanceof BankAccount;
    }

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

        return false;
    }


}
