<?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\User;
use Chill\MainBundle\Export\ExportManager;
use Chill\MainBundle\Repository\ExportGenerationRepository;
use Chill\MainBundle\Security\Authorization\ChillExportVoter;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use Twig\Environment;

final readonly class ExportIndexController
{
    public function __construct(
        private ExportManager $exportManager,
        private Environment $twig,
        private ExportGenerationRepository $exportGenerationRepository,
        private Security $security,
    ) {}

    /**
     * Render the list of available exports.
     */
    #[Route(path: '/{_locale}/exports/', name: 'chill_main_export_index')]
    public function indexAction(ExportController $exportController): Response
    {
        $user = $this->security->getUser();
        if (!$user instanceof User) {
            throw new AccessDeniedHttpException('Only regular user can see this page');
        }

        if (!$this->security->isGranted(ChillExportVoter::COMPOSE_EXPORT)) {
            throw new AccessDeniedHttpException(sprintf('Require the %s role', ChillExportVoter::COMPOSE_EXPORT));
        }

        $exports = $this->exportManager->getExportsGrouped(true);

        $lastExecutions = [];
        foreach ($this->exportManager->getExports() as $alias => $export) {
            $lastExecutions[$alias] = $this->exportGenerationRepository->findExportGenerationByAliasAndUser($alias, $user, 5);
        }

        return new Response(
            $this->twig->render('@ChillMain/Export/layout.html.twig', [
                'grouped_exports' => $exports,
                'last_executions' => $lastExecutions,
            ]),
        );
    }
}
