<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\PersonBundle\Command;

use Chill\PersonBundle\Actions\Remove\PersonMove;
use Chill\PersonBundle\Entity\Person;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Exception\RuntimeException;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

final class ChillPersonMoveCommand extends Command
{
    protected static $defaultDescription = 'Move all the associated entities on a "from" person to a "to" person and remove the old person';

    public function __construct(
        private readonly PersonMove $mover,
        private readonly EntityManagerInterface $em,
        private readonly LoggerInterface $chillLogger,
    ) {
        parent::__construct('chill:person:move');
    }

    protected function buildLoggingContext(Person $from, Person $to, $deleteEntities, $sqls)
    {
        $ctxt = [
            'from' => $from->getId(),
            'to' => $to->getId(),
        ];

        foreach ($deleteEntities as $key => $de) {
            $ctxt['delete_entity_'.$key] = $de;
        }

        foreach ($sqls as $key => $sql) {
            $ctxt['sql_'.$key] = $sql;
        }

        return $ctxt;
    }

    protected function configure()
    {
        $this
            ->setName('chill:person:move')
            ->addOption('from', 'f', InputOption::VALUE_REQUIRED, 'The person id to delete, all associated data will be moved before')
            ->addOption('to', 't', InputOption::VALUE_REQUIRED, 'The person id which will received data')
            ->addOption('dump-sql', null, InputOption::VALUE_NONE, 'dump sql to stdout')
            ->addOption('force', null, InputOption::VALUE_NONE, 'execute sql instead of dumping it')
            ->addOption('delete-entity', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'entity to delete', []);
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $repository = $this->em->getRepository(Person::class);
        $from = $repository->find($input->getOption('from'));
        $to = $repository->find($input->getOption('to'));
        $deleteEntities = $input->getOption('delete-entity');

        if (null === $from) {
            throw new RuntimeException(sprintf('Person "from" with id %d not found', $input->getOption('from')));
        }

        if (null === $to) {
            throw new RuntimeException(sprintf('Person "to" with id %d not found', $input->getOption('to')));
        }

        $sqls = $this->mover->getSQL($from, $to, $deleteEntities);

        if ($input->getOption('dump-sql')) {
            foreach ($sqls as $sql) {
                $output->writeln($sql);
            }
        } else {
            $ctxt = $this->buildLoggingContext($from, $to, $deleteEntities, $sqls);
            $this->chillLogger->notice('Trying to move a person from command line', $ctxt);
            $connection = $this->em->getConnection();
            $connection->beginTransaction();

            foreach ($sqls as $sql) {
                if ($output->isVerbose()) {
                    $output->writeln($sql);
                }
                $connection->executeQuery($sql);
            }
            $connection->commit();

            $this->chillLogger->notice('Move a person from command line succeeded', $ctxt);
        }

        return Command::SUCCESS;
    }

    protected function interact(InputInterface $input, OutputInterface $output)
    {
        if (false === $input->hasOption('dump-sql') && false === $input->hasOption('force')) {
            $msg = 'You must use "--dump-sql" or "--force"';

            throw new RuntimeException($msg);
        }

        foreach (['from', 'to'] as $name) {
            if (empty($input->getOption($name))) {
                throw new RuntimeException("You must set a \"{$name}\" option");
            }
            $id = $input->getOption($name);

            if (false === \ctype_digit((string) $id)) {
                throw new RuntimeException("The id in \"{$name}\" field does not contains only digits: {$id}");
            }
        }
    }
}
