<?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\Entity\Workflow\EntityWorkflow;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Workflow\Registry;

final class EntityWorkflowAttachmentVoter extends Voter
{
    public function __construct(
        private readonly Registry $registry,
    ) {}
    public const EDIT = 'CHILL_MAIN_WORKFLOW_ATTACHMENT_EDIT';

    protected function supports(string $attribute, $subject): bool
    {
        return $subject instanceof EntityWorkflow && self::EDIT === $attribute;
    }

    protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
    {
        if (!$subject instanceof EntityWorkflow) {
            throw new \UnexpectedValueException('Subject must be an instance of EntityWorkflow');
        }

        if ($subject->isFinal()) {
            return false;
        }

        $workflow = $this->registry->get($subject, $subject->getWorkflowName());

        $marking = $workflow->getMarking($subject);
        foreach ($marking->getPlaces() as $place => $int) {
            $placeMetadata = $workflow->getMetadataStore()->getPlaceMetadata($place);
            if ($placeMetadata['isSentExternal'] ?? false) {
                return false;
            }
        }

        return true;
    }
}
