<?php

namespace NoahVet\Reef\Infrastructure\Http\Get;

use NoahVet\Reef\Domain\Serialization\Jane\JaneSerializerFacadeInterface;
use NoahVet\Reef\Domain\Serialization\Json\JsonSerializerFacadeInterface;
use NoahVet\Reef\Domain\Serialization\Service\GetOneServiceInterface as SelfInterface;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;

class GetOneService implements SelfInterface
{
    public function __construct(
        protected readonly JaneSerializerFacadeInterface $janeSerializer,
        protected readonly JsonSerializerFacadeInterface $serializer,
    ) {
    }

    #[\Override]
    public function execute(
        object $object,
        array $normalizationAttributes,
        string $janeModelFQCN,
        ?string $locale = null,
        ?callable $postNormalize = null,
    ): array {
        $context = [AbstractNormalizer::ATTRIBUTES => $normalizationAttributes];

        if (null !== $locale) {
            $context['locale'] = $locale;
        }

        $data = (array) $this->serializer->normalize(
            data: $object,
            context: $context,
        );

        if (null !== $postNormalize) {
            $postNormalize($data, $locale);
        }

        return $this->janeSerializer->normalize(
            object: $this->janeSerializer->denormalize(
                data: $data,
                type: $janeModelFQCN,
            ),
        );
    }
}
