<?php

declare(strict_types=1);

namespace NoahVet\Reef\Controller\Common;

use NoahVet\Reef\Controller\AbstractController;
use NoahVet\Reef\Mapper\Common\One\Create\AbstractCreateMapperInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;

/**
 * @template EntityType of object
 * @template RequestDtoType of object
 * @template ResponseDtoType of object
 */
abstract class AbstractCreateController extends AbstractController
{
    /**
     * @param AbstractCreateMapperInterface<EntityType, RequestDtoType, ResponseDtoType> $mapper
     * @param class-string<RequestDtoType>                                               $requestDtoFqcn
     *
     * @return EntityType
     */
    protected function deserializeRequest(
        AbstractCreateMapperInterface $mapper,
        string $requestDtoFqcn,
    ): object {
        return $mapper->mapRequestDtoToEntity(
            $mapper->mapDataToRequestDto(
                $this->request->getContent(),
                $requestDtoFqcn,
            ),
        );
    }

    /**
     * @param array<string, mixed> $data
     */
    protected function getResponse(array $data): Response
    {
        return new JsonResponse(
            $data,
            Response::HTTP_CREATED,
            $this->headers,
        );
    }

    /**
     * @param AbstractCreateMapperInterface<EntityType, RequestDtoType, ResponseDtoType> $mapper
     * @param EntityType                                                                 $entity
     * @param class-string<ResponseDtoType>                                              $responseDtoFqcn
     *
     * @return array<string, mixed>
     */
    protected function serializeResponse(
        AbstractCreateMapperInterface $mapper,
        object $entity,
        string $responseDtoFqcn,
    ): array {
        return $mapper->normalizeResponseDto(
            $mapper->mapEntityToResponseDto(
                $entity,
                $responseDtoFqcn,
            ),
        );
    }
}
