<?php

namespace App\MessageHandler;

use App\Entity\Campaign;
use App\Entity\Link;
use App\Entity\Prospect;
use App\Message\IpChangedMessage;
use App\Service\CampaignService;
use App\Service\LinkService;
use App\Service\ProspectService;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;

class ChangeLinkIpMessageHandler implements MessageHandlerInterface
{
    /**
     * @var LinkService
     */
    private $linkService;
    /**
     * @var ProspectService
     */
    private $prospectService;
    /**
     * @var CampaignService
     */
    private $campaignService;

    public function __construct(ProspectService $prospectService, CampaignService $campaignService, LinkService $linkService)
    {
        $this->linkService = $linkService;
        $this->prospectService = $prospectService;
        $this->campaignService = $campaignService;
    }

    public function __invoke(IpChangedMessage $message)
    {
        //prospects with domain
        $prospects = $this->prospectService->getByDomain($message->getDomain()->getId());
        $prospectIds = array_map(function (Prospect $prospect) { return $prospect->getId(); }, $prospects);

        $linksWithProspects = $this->linkService->getByProspect($prospectIds);

        /** @var Link $link */
        foreach ($linksWithProspects as $link) {
            $link->setIpFrom($message->getDomain()->getIp());
            $this->linkService->save($link);
        }

        //campaigns with domain
        $campaigns = $this->campaignService->getByDomain($message->getDomain()->getId());

        $campaignIds = array_map(function (Campaign $campaign) { return $campaign->getId(); }, $campaigns);

        $linksWithCampaign = $this->linkService->getByCampaign($campaignIds);

        /** @var Link $link */
        foreach ($linksWithCampaign as $link) {
            $link->setIpTo($message->getDomain()->getIp());
            $this->linkService->save($link);
        }
    }
}
