<?php

namespace App\MessageHandler;

use App\Entity\Campaign\LandingPage\PageAuthority;
use App\Message\LandingPagePAMessage;
use App\Service\Campaign\LandingPage\PageAuthorityService;
use App\Service\Campaign\LandingPageService;
use Doctrine\ORM\EntityNotFoundException;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;

final class LandingPagePAMessageHandler implements MessageHandlerInterface
{
    /**
     * @var LandingPageService
     */
    private $landingPageService;
    /**
     * @var PageAuthorityService
     */
    private $pageAuthorityService;

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

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

        $pageAuthority = (new PageAuthority())
            ->setLandingPage($landingPage)
            ->setValue($message->getValue());

        $this->pageAuthorityService->save($pageAuthority);
    }
}
