<?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\Entity\NewsItem;
use Chill\MainBundle\Pagination\PaginatorFactory;
use Chill\MainBundle\Repository\NewsItemRepository;
use Chill\MainBundle\Templating\Listing\FilterOrderHelper;
use Chill\MainBundle\Templating\Listing\FilterOrderHelperFactoryInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Twig\Environment;

final readonly class NewsItemHistoryController
{
    public function __construct(
        private readonly NewsItemRepository $newsItemRepository,
        private readonly PaginatorFactory $paginatorFactory,
        private readonly FilterOrderHelperFactoryInterface $filterOrderHelperFactory,
        private readonly Environment $environment,
    ) {}

    #[Route(path: '/{_locale}/news-items/history', name: 'chill_main_news_items_history')]
    public function list(): Response
    {
        $filter = $this->buildFilterOrder();
        $total = $this->newsItemRepository->countAllFilteredBySearchTerm($filter->getQueryString());
        $newsItems = $this->newsItemRepository->findAllFilteredBySearchTerm($filter->getQueryString());

        $pagination = $this->paginatorFactory->create($total);

        return new Response($this->environment->render('@ChillMain/NewsItem/news_items_history.html.twig', [
            'entities' => $newsItems,
            'paginator' => $pagination,
            'filter_order' => $filter,
        ]));
    }

    #[Route(path: '/{_locale}/news-items/{id}', name: 'chill_main_single_news_item')]
    public function showSingleItem(NewsItem $newsItem, Request $request): Response
    {
        return new Response($this->environment->render(
            '@ChillMain/NewsItem/show.html.twig',
            [
                'entity' => $newsItem,
            ]
        ));
    }

    private function buildFilterOrder(): FilterOrderHelper
    {
        $filterBuilder = $this->filterOrderHelperFactory
            ->create(self::class)
            ->addSearchBox();

        return $filterBuilder->build();
    }
}
