<?php

namespace App\MessageHandler;

use App\Message\ReportGeneratedMessage;
use App\Message\ReportPublishedMessage;
use App\Service\Campaign\Report\PdfService;
use Psr\Log\LoggerInterface;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
use Symfony\Component\Messenger\MessageBusInterface;

final class ReportPublishedMessageHandler implements MessageHandlerInterface
{
    /**
     * @var PdfService
     */
    private $pdfService;
    /**
     * @var LoggerInterface
     */
    private $logger;
    /**
     * @var MessageBusInterface
     */
    private $messageBus;

    public function __construct(PdfService $pdfService, LoggerInterface $logger, MessageBusInterface $messageBus)
    {
        $this->pdfService = $pdfService;
        $this->logger = $logger;
        $this->messageBus = $messageBus;
    }

    public function __invoke(ReportPublishedMessage $message)
    {
        $report = $message->getReport();

        try {
            $path = $this->pdfService->generate($report);
        } catch (\Exception $e) {
            $this->logger->error(sprintf('Report could not been generated for report %d', $report
                ->getId()));

            return;
        }

        $this->messageBus->dispatch(new ReportGeneratedMessage($report, $path));
    }
}
