<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Controller;

use Chill\MainBundle\Pagination\PaginatorFactory;
use Chill\MainBundle\Repository\NewsItemRepository;
use Chill\MainBundle\Serializer\Model\Collection;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\SerializerInterface;

class NewsItemApiController
{
    public function __construct(
        private readonly NewsItemRepository $newsItemRepository,
        private readonly SerializerInterface $serializer,
        private readonly PaginatorFactory $paginatorFactory,
    ) {}

    /**
     * Get list of news items filtered on start and end date.
     */
    #[Route(path: '/api/1.0/main/news/current.json', methods: ['get'])]
    public function listCurrentNewsItems(): JsonResponse
    {
        $total = $this->newsItemRepository->countCurrentNews();
        $paginator = $this->paginatorFactory->create($total);
        $newsItems = $this->newsItemRepository->findCurrentNews(
            $paginator->getItemsPerPage(),
            $paginator->getCurrentPage()->getFirstItemNumber()
        );

        return new JsonResponse($this->serializer->serialize(
            new Collection(array_values($newsItems), $paginator),
            'json',
            [
                AbstractNormalizer::GROUPS => ['read'],
            ]
        ), JsonResponse::HTTP_OK, [], true);
    }
}
