<?php

declare(strict_types=1);

namespace App\Engine\AdministratorUser\Command;

#[\Symfony\Component\Console\Attribute\AsCommand(name: "admin:administrator-user:set-password", description: "Set admin's password.")]
final class SetPasswordCommand extends \Symfony\Component\Console\Command\Command
{

    public function __construct(
        private readonly \App\Engine\AdministratorUser\AdministratorUserRepository               $administratorUserRepository,
        private readonly \Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactoryInterface $hasherFactory,
        private readonly \Doctrine\ORM\EntityManagerInterface                                    $entityManager,
    ) {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this->addArgument(name: "userId", mode: \Symfony\Component\Console\Input\InputOption::VALUE_REQUIRED);
    }

    protected function execute(\Symfony\Component\Console\Input\InputInterface $input, \Symfony\Component\Console\Output\OutputInterface $output): int
    {
        $style = new \Symfony\Component\Console\Style\SymfonyStyle($input, $output);
        $userId = $input->getArgument("userId");
        if ($userId === null) {
            $style->error("User id is required.");
            return \Symfony\Component\Console\Command\Command::FAILURE;
        }

        $user = $this->administratorUserRepository->findOneBy(["id" => $userId]);
        if ($user === null) {
            $style->error("User not found!");
            return \Symfony\Component\Console\Command\Command::FAILURE;
        }

        if (!($passwd = $style->askHidden("Password"))) {
            $style->error("Password must not be empty!");
            return \Symfony\Component\Console\Command\Command::FAILURE;
        }

        if ($style->askHidden("Repeat password") !== $passwd) {
            $style->error("Passwords must match!");
            return \Symfony\Component\Console\Command\Command::FAILURE;
        }

        $hasher = $this->hasherFactory->getPasswordHasher(\App\Engine\AdministratorUser\AdministratorUser::class);
        $user->setPassword($hasher->hash($passwd));
        $this->entityManager->persist($user);
        $this->entityManager->flush();

        $style->success("Password changed.");
        return \Symfony\Component\Console\Command\Command::SUCCESS;
    }

}
