<?php

declare(strict_types=1);

namespace NoahVet\Reef\Mapper\Common\Search;

use Doctrine\Common\Collections\ArrayCollection;
use NoahVet\Reef\Domain\Tool\ArrayTool;
use NoahVet\Reef\Mapper\AbstractMapper;
use Symfony\Component\Serializer\Exception\ExceptionInterface;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;

/**
 * @template EntityType of object
 * @template RequestDtoType of object
 * @template ResponseDtoType of object
 *
 * @implements AbstractSearchMapperInterface<EntityType, RequestDtoType, ResponseDtoType>
 */
abstract class AbstractSearchMapper extends AbstractMapper implements AbstractSearchMapperInterface
{
    /**
     * @var EntityType
     */
    protected object $entity;

    /**
     * @param class-string<RequestDtoType> $requestDto
     *
     * @return RequestDtoType
     */
    public function mapDataToRequestDto(
        string $data,
        string $requestDto,
    ): object {
        /** @var array<string, mixed> $dataAsArray */
        $dataAsArray = $this->serializer->decode(
            $data,
            'json',
        );

        ArrayTool::applyTrimRecursive($dataAsArray);

        return $this->serializer->denormalize(
            $dataAsArray,
            $requestDto,
            'json',
            [
                AbstractNormalizer::ALLOW_EXTRA_ATTRIBUTES => false,
            ],
        );
    }

    /**
     * @param array<int, EntityType>        $data
     * @param class-string<ResponseDtoType> $responseDtoFqcn
     *
     * @return list<ResponseDtoType>
     *
     * @throws ExceptionInterface
     *
     * @psalm-suppress InvalidReturnStatement
     */
    public function mapDataToResponseDto(
        array $data,
        string $responseDtoFqcn,
    ): mixed {
        $data = $this->normalizeEntities(
            new ArrayCollection($data),
        );

        foreach ($data as &$datum) {
            $this->postNormalizeEntity($datum);
        }

        return $this->serializer->denormalize(
            $data,
            $responseDtoFqcn.'[]',
        );
    }

    /**
     * @param list<ResponseDtoType> $dtoAsArray
     *
     * @return list<mixed>
     *
     * @throws ExceptionInterface
     */
    public function normalizeResponseDto(
        array $dtoAsArray,
    ): array {
        return \array_values((array) $this->serializer->normalize($dtoAsArray));
    }

    /**
     * @param array<string, mixed> $data
     */
    protected function postNormalizeEntity(array &$data): void
    {
    }
}
