<?php

namespace App\Command\App\Get;

use App\Entity\Country;
use App\Integrations\Semrush\Client;
use App\Integrations\Semrush\Requests\GetCountriesRequest;
use App\Service\CountryService;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

class CountriesCommand extends Command
{
    protected static $defaultName = 'app:get:countries';
    /**
     * @var GetCountriesRequest
     */
    private $request;
    /**
     * @var Client
     */
    private $client;
    /**
     * @var CountryService
     */
    private $countryService;

    public function __construct(Client $client, GetCountriesRequest $request, CountryService $countryService, ?string $name = null)
    {
        parent::__construct($name);
        $this->request = $request;
        $this->client = $client;
        $this->countryService = $countryService;
    }

    protected function configure()
    {
        $this
            ->setDescription('Get Countries for Country entity from external API');
    }

    /**
     * @return void
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $io = new SymfonyStyle($input, $output);

        $response = $this->client->execute($this->request);

        foreach ($response->getBody() as $countryData) {
            $this->countryService->save((new Country())->setTitle($countryData['name'])->setSemrushId((int) $countryData['id']));
        }

        $io->success(sprintf('Imported %s countries', count($response->getBody())));
    }
}
