<?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\Export\Messenger;

use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\DocStoreBundle\Service\StoredObjectManagerInterface;
use Chill\MainBundle\Export\ExportGenerator;
use Chill\MainBundle\Repository\ExportGenerationRepository;
use Chill\MainBundle\Repository\UserRepositoryInterface;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Messenger\Exception\UnrecoverableMessageHandlingException;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;

#[AsMessageHandler]
final readonly class ExportRequestGenerationMessageHandler implements MessageHandlerInterface
{
    private const LOG_PREFIX = '[export_generation] ';

    public function __construct(
        private ExportGenerationRepository $repository,
        private UserRepositoryInterface $userRepository,
        private ExportGenerator $exportGenerator,
        private StoredObjectManagerInterface $storedObjectManager,
        private EntityManagerInterface $entityManager,
        private LoggerInterface $logger,
    ) {}

    public function __invoke(ExportRequestGenerationMessage $exportRequestGenerationMessage)
    {
        $start = microtime(true);

        $this->logger->info(
            self::LOG_PREFIX.'Handle generation message',
            [
                'exportId' => (string) $exportRequestGenerationMessage->id,
            ]
        );

        if (null === $exportGeneration = $this->repository->find($exportRequestGenerationMessage->id)) {
            throw new \UnexpectedValueException('ExportRequestGenerationMessage not found');
        }

        if (null === $user = $this->userRepository->find($exportRequestGenerationMessage->userId)) {
            throw new \UnexpectedValueException('User not found');
        }

        if (StoredObject::STATUS_PENDING !== $exportGeneration->getStatus()) {
            throw new UnrecoverableMessageHandlingException('object already generated');
        }

        $generated = $this->exportGenerator->generate($exportGeneration->getExportAlias(), $exportGeneration->getOptions(), $user);
        $this->storedObjectManager->write($exportGeneration->getStoredObject(), $generated->content, $generated->contentType);
        $exportGeneration->getStoredObject()->setStatus(StoredObject::STATUS_READY);

        $this->entityManager->flush();

        $end = microtime(true);

        $this->logger->notice(self::LOG_PREFIX.'Export generation successfully finished', [
            'exportId' => (string) $exportRequestGenerationMessage->id,
            'exportAlias' => $exportGeneration->getExportAlias(),
            'full_generation_duration' => $end - $exportGeneration->getCreatedAt()->getTimestamp(),
            'message_handler_duration' => $end - $start,
        ]);
    }
}
