<?php

namespace Shared\TransferSync\Voter;

use Shared\TransferSync\Entity\IndividualStructureChange;
use Shared\TransferSync\Entity\UnitParcelStructureChange;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;

/**
 * Class IndividualStructureChangeVoter
 * @package Shared\TransferSync\Voter
 */
class IndividualStructureChangeVoter extends Voter
{
    public const STRUCTURE_CHANGE_GET_PATCH = 'STRUCTURE_CHANGE_GET_PATCH';

    private Security $security;

    public function __construct(Security $security)
    {
        $this->security = $security;
    }

    protected function supports($attribute, $subject): bool
    {
        $supportsAttribute = in_array($attribute, [self::STRUCTURE_CHANGE_GET_PATCH]);
        $supportsSubject = $subject instanceof IndividualStructureChange || $subject instanceof UnitParcelStructureChange;
        return $supportsAttribute && $supportsSubject;
    }

    /**
     * @param string $attribute
     * @param IndividualStructureChange $subject
     * @param TokenInterface $token
     * @return bool
     */
    protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
    {
        if (!$token->isAuthenticated()) {
            return false;
        }
        $site = $subject->getStatusDataEntry()->getWebappProject()->getPlatform()->getSite();
        switch ($attribute) {
            case self::STRUCTURE_CHANGE_GET_PATCH:
                return $this->security->isGranted('ROLE_PLATFORM_MANAGER', $site) ||
                    $subject->getStatusDataEntry()->getWebappProject()->getOwner() === $token->getUser();
        }

        return false;
    }
}
