<?php

declare(strict_types=1);

namespace NoahVet\Reef\Controller\Common;

use NoahVet\Reef\Controller\AbstractController;
use NoahVet\Reef\Factory\RequestContext\RequestContextFactoryInterface;
use NoahVet\Reef\Mapper\Common\Many\AbstractGetAllMapperInterface;
use NoahVet\Reef\Paginator\HttpPaginatorInterface;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Response;

/**
 * @template EntityType of object
 * @template ResponseDtoType of object
 */
abstract class AbstractExportXlsxController extends AbstractController
{
    public function __construct(
        protected readonly HttpPaginatorInterface $httpPaginator,
        protected readonly RequestContextFactoryInterface $requestContextFactory,
    ) {
    }

    protected function getResponse(string $filePath): BinaryFileResponse
    {
        if (0 < $this->httpPaginator->getInformation()['last']) {
            $this->headers = \array_merge($this->headers, $this->httpPaginator->getContentRangeHeader('resources'));
        }

        return new BinaryFileResponse(
            $filePath,
            0 < $this->httpPaginator->getInformation()['last'] ? Response::HTTP_PARTIAL_CONTENT : Response::HTTP_OK,
            $this->headers,
        );
    }

    /**
     * @param AbstractGetAllMapperInterface<EntityType, ResponseDtoType> $mapper
     * @param class-string<EntityType>                                   $entityFqcn
     * @param class-string<ResponseDtoType>                              $responseDtoFqcn
     *
     * @return array<int, ResponseDtoType>
     */
    protected function serializeResponse(
        AbstractGetAllMapperInterface $mapper,
        string $entityFqcn,
        string $responseDtoFqcn,
        bool $isPaginated = true,
    ): array {
        return $mapper->normalizeResponseDto(
            $mapper->mapDataToResponseDto(
                $this->httpPaginator->getResult(
                    $this->request,
                    $entityFqcn,
                    $this->requestContextFactory->createContextFromRequest(
                        $this->request,
                        $this->whitelist,
                    ),
                    $isPaginated,
                ),
                $responseDtoFqcn,
            ),
        );
    }
}
