<?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\ExportGeneration;
use Chill\MainBundle\Export\ExportManager;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\SerializerInterface;
use Twig\Environment;

final readonly class ExportGenerationController
{
    public function __construct(
        private Security $security,
        private Environment $twig,
        private SerializerInterface $serializer,
        private ExportManager $exportManager,
    ) {}

    #[Route('/{_locale}/main/export-generation/{id}/wait', methods: ['GET'], name: 'chill_main_export-generation_wait')]
    public function wait(ExportGeneration $exportGeneration): Response
    {
        if (!$this->security->isGranted('ROLE_USER')) {
            throw new AccessDeniedHttpException('Only users can download an export');
        }

        $export = $this->exportManager->getExport($exportGeneration->getExportAlias());

        return new Response(
            $this->twig->render('@ChillMain/ExportGeneration/wait.html.twig', ['exportGeneration' => $exportGeneration, 'export' => $export]),
        );
    }

    #[Route('/api/1.0/main/export-generation/{id}/object', methods: ['GET'])]
    public function objectStatus(ExportGeneration $exportGeneration): JsonResponse
    {
        if (!$this->security->isGranted('ROLE_USER')) {
            throw new AccessDeniedHttpException('Only users can download an export');
        }

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