<?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\GetAllServiceInterface as SelfInterface;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;

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

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

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

        $rawObjects = \array_values(
            (array) $this->serializer->normalize(
                data: $objects,
                context: $context,
            ),
        );

        if (null !== $postNormalize) {
            foreach ($rawObjects as &$item) {
                $postNormalize($item, $locale);
            }
            unset($item);
        }

        return \array_map(
            fn (array $item): array => $this->janeSerializer->normalize(
                object: $this->janeSerializer->denormalize(
                    data: $item,
                    type: $janeModelFQCN,
                ),
            ),
            $rawObjects,
        );
    }
}
