<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Security\Authorization;

use Chill\MainBundle\Repository\Workflow\EntityWorkflowRepository;
use Chill\MainBundle\Workflow\EntityWorkflowHandlerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;

class WorkflowEntityDeletionVoter extends Voter
{
    /**
     * @param EntityWorkflowHandlerInterface[] $handlers
     */
    public function __construct(private $handlers, private readonly EntityWorkflowRepository $entityWorkflowRepository) {}

    protected function supports($attribute, $subject)
    {
        if (!\is_object($subject)) {
            return false;
        }

        foreach ($this->handlers as $handler) {
            if ($handler->isObjectSupported($subject)
                && \in_array($attribute, $handler->getDeletionRoles(), true)) {
                return true;
            }
        }

        return false;
    }

    protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
    {
        foreach ($this->handlers as $handler) {
            if ($handler->isObjectSupported($subject)) {
                return 0 === $this->entityWorkflowRepository->countRelatedWorkflows(
                    $handler->getRelatedObjects($subject)
                );
            }
        }

        throw new \RuntimeException('no handlers found');
    }
}
