<?php

namespace App\Command;

use App\Entity\Research;
use App\Service\CampaignService;
use App\Service\Content\TypeService;
use App\Service\Research\StatusService;
use App\Service\ResearchService;
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;
use Webmozart\Assert\Assert;

class CrmMakeResearchCommand extends Command
{
    protected static $defaultName = 'crm:make:research';
    private $campaignService;
    /**
     * @var ResearchService
     */
    private $researchService;
    /**
     * @var StatusService
     */
    private $researchStatusService;
    /**
     * @var TypeService
     */
    private $contentTypeService;

    public function __construct(ResearchService $researchService, CampaignService $campaignService, StatusService $researchStatusService, TypeService $contentTypeService, $name = null)
    {
        parent::__construct($name);
        $this->campaignService = $campaignService;
        $this->researchService = $researchService;
        $this->researchStatusService = $researchStatusService;
        $this->contentTypeService = $contentTypeService;
    }

    protected function configure()
    {
        $this
            ->setDescription('Add a Research')
            ->addArgument('campaign', InputArgument::REQUIRED, 'Campaign which Research will be assigned to')
            ->addArgument('contentType', InputArgument::REQUIRED, 'Content type for research');
    }

    protected function execute(InputInterface $input, OutputInterface $output): ?int
    {
        $io = new SymfonyStyle($input, $output);

        $io->note(sprintf('You passed arguments: %s, %s', $input->getArgument('campaign'), $input->getArgument('contentType')));

        try {
            Assert::integerish($input->getArgument('contentType'));
            $campaign = $this->campaignService->getCampaign($input->getArgument('campaign'));
            $contentType = $this->contentTypeService->get($input->getArgument('contentType'));
        } catch (\Exception $e) {
            $io->error($e->getMessage());

            return 1;
        }

        $status = $this->researchStatusService->getFirst();

        $research = (new Research())
            ->setCampaign($campaign)
            ->setStatus($status)
            ->setContentType($contentType);

        $this->researchService->save($research);

        $io->success('Research created');
    }
}
