<?php

namespace App\MessageHandler;

use App\Entity\Campaign\LandingPage\BacklinksReport;
use App\Message\LandingPageBacklinksMessage;
use App\Service\Campaign\LandingPage\BacklinksReportService;
use App\Service\Campaign\LandingPageService;
use Doctrine\ORM\EntityNotFoundException;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;

final class LandingPageBacklinksMessageHandler implements MessageHandlerInterface
{
    /**
     * @var LandingPageService
     */
    private $landingPageService;
    /**
     * @var BacklinksReportService
     */
    private $backlinksReportService;

    public function __construct(LandingPageService $landingPageService, BacklinksReportService $backlinksReportService)
    {
        $this->landingPageService = $landingPageService;
        $this->backlinksReportService = $backlinksReportService;
    }

    public function __invoke(LandingPageBacklinksMessage $message)
    {
        try {
            $landingPage = $this->landingPageService->get($message->getLandingPageId());
        } catch (EntityNotFoundException $e) {
            return;
        }

        $backlinksReport = (new BacklinksReport())
            ->setLandingPage($landingPage)
            ->setDescription($message->getValue());

        $this->backlinksReportService->save($backlinksReport);
    }
}
