<?php

namespace App\Command\Crm\Link;

use App\Service\LinkService;
use Doctrine\ORM\EntityNotFoundException;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

class IpCommand extends Command
{
    protected static $defaultName = 'crm:link:ip';
    /**
     * @var LinkService
     */
    private $linkService;

    public function __construct(LinkService $linkService, ?string $name = null)
    {
        parent::__construct($name);
        $this->linkService = $linkService;
    }

    protected function configure()
    {
        $this
            ->setDescription('Checks ipFrom and ipTo for given Link')
            ->addArgument('linkId', InputArgument::REQUIRED, 'Link to check');
    }

    protected function execute(InputInterface $input, OutputInterface $output): void
    {
        $io = new SymfonyStyle($input, $output);
        $linkId = $input->getArgument('linkId');

        try {
            $link = $this->linkService->get($linkId);
        } catch (EntityNotFoundException $e) {
            $io->error('There is no Link for given ID');

            return;
        }

        $io->writeln(sprintf('Checking: %s', $link->getUrl()));

        if ($link->getProspect() && $link->getProspect()->getDomain()) {
            $link->setIpFrom($link->getProspect()->getDomain()->getIp());
        }
        if ($link->getContent() && $link->getContent()->getCampaign() && $link->getContent()->getCampaign()->getDomain()) {
            $link->setIpTo($link->getContent()->getCampaign()->getDomain()->getIp());
        }

        $this->linkService->save($link);

        $io->success('Finished!');
    }
}
