<?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\DocStoreBundle\GenericDoc\Manager;
use Chill\DocStoreBundle\Serializer\Normalizer\GenericDocNormalizer;
use Chill\MainBundle\Entity\Workflow\EntityWorkflowAttachment;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class EntityWorkflowAttachmentNormalizer implements NormalizerInterface, NormalizerAwareInterface
{
    use NormalizerAwareTrait;

    public const LINKED = 'entity_workflow_attachment_linked';

    public function __construct(
        private readonly Manager $manager,
    ) {}

    public function normalize($object, $format = null, array $context = []): array
    {
        /** @var EntityWorkflowAttachment $object */
        $genericDoc = $this->manager->buildOneGenericDoc($object->getRelatedGenericDocKey(), $object->getRelatedGenericDocIdentifiers());

        return [
            'id' => $object->getId(),
            'relatedGenericDocKey' => $object->getRelatedGenericDocKey(),
            'relatedGenericDocIdentifiers' => $object->getRelatedGenericDocIdentifiers(),
            'createdAt' => $this->normalizer->normalize($object->getCreatedAt(), $format, $context),
            'createdBy' => $this->normalizer->normalize($object->getCreatedBy(), $format, $context),
            'updatedAt' => $this->normalizer->normalize($object->getUpdatedAt(), $format, $context),
            'updatedBy' => $this->normalizer->normalize($object->getUpdatedBy(), $format, $context),
            'genericDoc' => $this->normalizer->normalize($genericDoc, $format, [
                GenericDocNormalizer::ATTACHED_STORED_OBJECT_PROXY => $object->getProxyStoredObject(), ...$context,
            ]),
        ];
    }

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