<?php

namespace Webapp\Core\Voter;

use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Webapp\Core\Entity\SemiAutomaticVariable;
use Webapp\Core\Service\TestRepository;

class SemiAutoVariableVoter extends Voter
{
    public const SEMI_AUTO_VARIABLE_DELETE = 'SEMI_AUTO_VARIABLE_DELETE';

    private TestRepository $testRepository;

    public function __construct(
        TestRepository $testRepository
    )
    {
        $this->testRepository = $testRepository;
    }

    protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
    {
        /** @var SemiAutomaticVariable $semiAutoVariable */
        $semiAutoVariable = $subject;

        if (self::SEMI_AUTO_VARIABLE_DELETE === $attribute) {
            if ($this->testRepository->isVariableInUse($semiAutoVariable)) {
                throw new AccessDeniedException('semiAutoVariable.deleteOperation.testOrSaisieStillConnected');
            }
        }

        return true;
    }

    protected function supports(string $attribute, $subject): bool
    {
        return in_array($attribute, [self::SEMI_AUTO_VARIABLE_DELETE]) && is_a($subject, SemiAutomaticVariable::class);
    }
}
