<?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\Workflow;

use Chill\MainBundle\Entity\Workflow\EntityWorkflow;
use Symfony\Component\Workflow\Marking;
use Symfony\Component\Workflow\MarkingStore\MarkingStoreInterface;

final readonly class EntityWorkflowMarkingStore implements MarkingStoreInterface
{
    public function getMarking(object $subject): Marking
    {
        if (!$subject instanceof EntityWorkflow) {
            throw new \UnexpectedValueException('Expected instance of EntityWorkflow');
        }
        $step = $subject->getCurrentStep();

        return new Marking([$step->getCurrentStep() => 1]);
    }

    public function setMarking(object $subject, Marking $marking, array $context = []): void
    {
        if (!$subject instanceof EntityWorkflow) {
            throw new \UnexpectedValueException('Expected instance of EntityWorkflow');
        }

        $places = $marking->getPlaces();
        if (1 < count($places)) {
            throw new \LogicException('Expected maximum one place');
        }
        $next = array_keys($places)[0];

        $transitionDTO = $context['context'] ?? null;
        $transition = $context['transition'];
        $byUser = $context['byUser'] ?? null;
        $at = $context['transitionAt'];

        if (!$transitionDTO instanceof WorkflowTransitionContextDTO) {
            throw new \UnexpectedValueException(sprintf('Expected instance of %s', WorkflowTransitionContextDTO::class));
        }

        $subject->setStep($next, $transitionDTO, $transition, $at, $byUser);
    }
}
