<?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\MainBundle\Command;

use Chill\MainBundle\Entity\User;
use Doctrine\ORM\EntityManager;
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\Security\Core\Encoder\EncoderFactory;

/**
 * Class SetPasswordCommand.
 */
class SetPasswordCommand extends Command
{
    protected static $defaultDescription = 'set a password to user';

    /**
     * SetPasswordCommand constructor.
     */
    public function __construct(private readonly EntityManager $entityManager)
    {
        parent::__construct();
    }

    public function _getUser($username)
    {
        return $this->entityManager
            ->getRepository(User::class)
            ->findOneBy(['username' => $username]);
    }

    public function _setPassword(User $user, $password)
    {
        $defaultEncoder = new \Symfony\Component\PasswordHasher\Hasher\MessageDigestPasswordHasher('sha512', true, 5000);
        $encoders = [
            User::class => $defaultEncoder,
        ];
        $encoderFactory = new EncoderFactory($encoders);
        $user->setPassword(
            $encoderFactory->getEncoder($user)->encodePassword($password, $user->getSalt())
        );
        $this->entityManager->flush($user);
    }

    public function configure()
    {
        $this->setName('chill:user:set_password')
            ->addArgument('username', InputArgument::REQUIRED, 'the user\'s '
                    .'username you want to change password')
            ->addArgument('password', InputArgument::OPTIONAL, 'the new password');
    }

    public function execute(InputInterface $input, OutputInterface $output): int
    {
        $user = $this->_getUser($input->getArgument('username'));

        if (null === $user) {
            throw new \LogicException("The user with username '".$input->getArgument('username')."' is not found");
        }

        $password = $input->getArgument('password');

        if (null === $password) {
            $dialog = $this->getHelperSet()->get('dialog');
            $password = $dialog->askHiddenResponse($output, '<question>the new password :'
                  .'</question>');
        }

        $this->_setPassword($user, $password);

        return Command::SUCCESS;
    }
}
