<?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\Serializer\Normalizer;

use Chill\MainBundle\Entity\Workflow\EntityWorkflowStep;
use Chill\MainBundle\Workflow\Helper\MetadataExtractor;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class EntityWorkflowStepNormalizer implements NormalizerAwareInterface, NormalizerInterface
{
    use NormalizerAwareTrait;

    public function __construct(private readonly MetadataExtractor $metadataExtractor) {}

    /**
     * @param EntityWorkflowStep $object
     */
    public function normalize($object, ?string $format = null, array $context = []): array
    {
        $data = [
            'type' => 'entity_workflow_step',
            'id' => $object->getId(),
            'comment' => $object->getComment(),
            'currentStep' => $this->metadataExtractor->buildArrayPresentationForPlace($object->getEntityWorkflow(), $object),
            'isFinal' => $object->isFinal(),
            'isFreezed' => false,
            'isFinalized' => false,
            'transitionPrevious' => null,
            'transitionAfter' => null,
            'previousId' => null,
            'nextId' => null,
            'transitionPreviousBy' => null,
            'transitionPreviousAt' => null,
        ];

        if (null !== $previous = $object->getPrevious()) {
            $data['transitionPrevious'] = $this->metadataExtractor
                ->buildArrayPresentationForTransition($object->getEntityWorkflow(), $object->getPrevious()->getTransitionAfter());
            $data['previousId'] = $previous->getId();
            $data['isFreezed'] = $previous->isFreezeAfter();
            $data['transitionPreviousBy'] = $this->normalizer->normalize(
                $previous->getTransitionBy(),
                $format,
                [...$context, UserNormalizer::AT_DATE => $previous->getTransitionAt()]
            );
            $data['transitionPreviousAt'] = $this->normalizer->normalize(
                $previous->getTransitionAt(),
                $format,
                $context
            );
        }

        if (null !== $next = $object->getNext()) {
            $data['nextId'] = $next->getId();
        }

        if (null !== $object->getTransitionAfter()) {
            $data['transitionAfter'] = $this->metadataExtractor->buildArrayPresentationForTransition(
                $object->getEntityWorkflow(),
                $object->getTransitionAfter()
            );
        }

        return $data;
    }

    public function supportsNormalization($data, ?string $format = null): bool
    {
        return $data instanceof EntityWorkflowStep && 'json' === $format;
    }
}
