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

use Chill\MainBundle\Repository\Workflow\EntityWorkflowRepository;
use Chill\MainBundle\Workflow\Helper\MetadataExtractor;
use Chill\PersonBundle\Entity\AccompanyingPeriod\AccompanyingPeriodWorkEvaluationDocument;
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
use Symfony\Component\Workflow\Registry;

class AccompanyingPeriodWorkEvaluationDocumentNormalizer implements ContextAwareNormalizerInterface, NormalizerAwareInterface
{
    use NormalizerAwareTrait;

    private const SKIP = 'accompanying_period_work_evaluation_document_skip';

    public function __construct(private readonly EntityWorkflowRepository $entityWorkflowRepository, private readonly MetadataExtractor $metadataExtractor, private readonly Registry $registry) {}

    public function normalize($object, ?string $format = null, array $context = []): array
    {
        $initial = $this->normalizer->normalize($object, $format, array_merge($context, [
            self::SKIP => spl_object_hash($object),
        ]));

        $initial['workflows_availables'] = $this->metadataExtractor->availableWorkflowFor(
            AccompanyingPeriodWorkEvaluationDocument::class,
            $object->getId()
        );

        $workflows = $this->entityWorkflowRepository->findBy([
            'relatedEntityClass' => AccompanyingPeriodWorkEvaluationDocument::class,
            'relatedEntityId' => $object->getId(),
        ]);
        $initial['workflows'] = $this->normalizer->normalize($workflows, 'json', $context);

        return $initial;
    }

    public function supportsNormalization($data, ?string $format = null, array $context = [])
    {
        return $data instanceof AccompanyingPeriodWorkEvaluationDocument
            && 'json' === $format
            && (
                !\array_key_exists(self::SKIP, $context)
                || spl_object_hash($data) !== $context[self::SKIP]
            );
    }
}
