<?php

namespace NoahVet\Reef\Infrastructure\Http\Patch;

use NoahVet\Reef\Application\Port\PatchMergeResolverServiceInterface as SelfInterface;
use NoahVet\Reef\Application\Resolver\PatchMergeResolverInterface;
use NoahVet\Reef\Domain\Serialization\Json\JsonSerializerFacadeInterface;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;

class PatchMergeResolverService implements SelfInterface
{
    public function __construct(
        private readonly JsonSerializerFacadeInterface $serializer,
    ) {
    }

    #[\Override]
    public function __invoke(PatchMergeResolverInterface $resolver): array
    {
        $existingData = (array) $this->serializer->normalize(
            data: $resolver->existingEntity(),
            context: [AbstractNormalizer::ATTRIBUTES => $resolver->ateAttributes()],
        );

        $patchData = (array) (\json_decode($resolver->requestContent(), associative: true) ?? []);

        return \array_merge($existingData, $patchData);
    }
}
