<?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\EntityWorkflow;
use Chill\MainBundle\Security\Authorization\EntityWorkflowAttachmentVoter;
use Chill\MainBundle\Workflow\EntityWorkflowManager;
use Chill\MainBundle\Workflow\Helper\MetadataExtractor;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Workflow\Registry;

final class EntityWorkflowNormalizer implements NormalizerInterface, NormalizerAwareInterface
{
    use NormalizerAwareTrait;

    public function __construct(
        private readonly EntityWorkflowManager $entityWorkflowManager,
        private readonly MetadataExtractor $metadataExtractor,
        private readonly Registry $registry,
        private readonly Security $security,
    ) {}

    /**
     * @param EntityWorkflow $object
     *
     * @return array
     */
    public function normalize($object, ?string $format = null, array $context = [])
    {
        $workflow = $this->registry->get($object, $object->getWorkflowName());
        $handler = $this->entityWorkflowManager->getHandler($object);

        return [
            'type' => 'entity_workflow',
            'id' => $object->getId(),
            'relatedEntityClass' => $object->getRelatedEntityClass(),
            'relatedEntityId' => $object->getRelatedEntityId(),
            'workflow' => $this->metadataExtractor->buildArrayPresentationForWorkflow($workflow),
            'currentStep' => $this->normalizer->normalize($object->getCurrentStep(), $format, $context),
            'steps' => $this->normalizer->normalize($object->getStepsChained(), $format, $context),
            'datas' => $this->normalizer->normalize($handler->getEntityData($object), $format, $context),
            'title' => $handler->getEntityTitle($object),
            'isOnHoldAtCurrentStep' => $object->isOnHoldAtCurrentStep(),
            '_permissions' => [
                EntityWorkflowAttachmentVoter::EDIT => $this->security->isGranted(EntityWorkflowAttachmentVoter::EDIT, $object),
            ],
        ];
    }

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