<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\Commands;

use apexl\Io\exceptions\RecordNotFoundException;
use Exception;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(name: 'user:reset-password', description: 'Reset user password')]
class UserResetPasswordCommand extends AbstractUserCommand
{
    protected function configure(): void
    {
        parent::configure();

        $this->addArgument('idOrEmail', InputArgument::REQUIRED, 'The user ID or email');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);
        $idOrEmail = $input->getArgument('idOrEmail');

        try {
            $user = $this->getUser($idOrEmail);

            $helper = $this->getHelper('question');
            $question = new Question('Please enter the new password: ');
            $question->setHidden(true);
            $question->setHiddenFallback(false);

            $password = $helper->ask($input, $output, $question);

            $user->password = $password;

            $user->store();

            $io->success(sprintf('Password for user (%d / %s) has been reset.', $user->id, $user->email));

            return self::SUCCESS;
        } catch (RecordNotFoundException $e) {
            $io->error(sprintf('User with ID or email \'%s\' not found.', $idOrEmail));

            return self::FAILURE;
        } catch (Exception $e) {
            $io->error($e->getMessage());

            return self::FAILURE;
        }
    }
}
