<?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\Entity\SavedExport;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Export\Messenger\ExportRequestGenerationMessage;
use Chill\MainBundle\Security\Authorization\SavedExportVoter;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Serializer\SerializerInterface;

class ExportGenerationCreateFromSavedExportController
{
    public function __construct(
        private readonly Security $security,
        private readonly EntityManagerInterface $entityManager,
        private readonly MessageBusInterface $messageBus,
        private readonly ClockInterface $clock,
        private readonly SerializerInterface $serializer,
    ) {}

    #[Route('/api/1.0/main/export/export-generation/create-from-saved-export/{id}', methods: ['POST'])]
    public function __invoke(SavedExport $export): JsonResponse
    {
        if (!$this->security->isGranted(SavedExportVoter::GENERATE, $export)) {
            throw new AccessDeniedHttpException('Not allowed to generate an export from this saved export');
        }
        $user = $this->security->getUser();

        if (!$user instanceof User) {
            throw new AccessDeniedHttpException('Only users can create exports');
        }

        $exportGeneration = ExportGeneration::fromSavedExport($export, $this->clock->now()->add(new \DateInterval('P6M')));

        $this->entityManager->persist($exportGeneration);
        $this->entityManager->flush();

        $this->messageBus->dispatch(new ExportRequestGenerationMessage($exportGeneration, $user));

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