<?php
declare(strict_types=1);

namespace App\Security\Voter\EntityVoter\Core;

use App\Entity\Access\Access;
use App\Entity\Core\BankAccount;
use App\Security\Voter\EntityVoter\AbstractEntityVoter;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * Contrôle l'accès à l'entité BankAccount
 */
class BankAccountVoter extends AbstractEntityVoter
{
    /**
     * @inheritdoc
     */
    protected static ?string $entityClass = BankAccount::class;

    /**
     * @inheritdoc
     */
    protected static array $allowedOperations = [
        self::READ, self::EDIT, self::DELETE
    ];

    /**
     * Can the user interact with the BankAccount, with the given required role
     *
     * @param string $role The role needed to interract with the BankAccount
     * @return bool
     */
    private function canInteractIfHasRole(object $subject, string $role): bool {
        return $this->isUserLoggedIn()
            && $subject->getOrganization()->count() === 1
            && $this->security->isGranted($role)
            && $subject->getOrganization()->current()->getId() === $this->getUser()->getOrganization()->getId();
    }

    /**
     * @inheritdoc
     *
     * @param $subject BankAccount
     * @return boolean
     */
    protected function canView(object $subject): bool {
        return $this->canInteractIfHasRole($subject, 'ROLE_ORGANIZATION_VIEW');
    }

    /**
     * @inheritdoc
     *
     * @param $subject BankAccount
     * @return boolean
     */
    protected function canEdit(object $subject): bool {
        return $this->canInteractIfHasRole($subject, 'ROLE_ORGANIZATION');
    }

    /**
     * @inheritdoc
     *
     * @param $subject BankAccount
     * @return boolean
     */
    protected function canDelete(object $subject): bool {
        return $this->canEdit($subject);
    }
}
