<?php

namespace AutoAdmin\Bundle\Admin\Command\Admin;

use AutoAdmin\Bundle\Admin\Service\AdministratorManager;
use Exception;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Symfony\Component\Console\Question\Question;

#[AsCommand(name: 'aa:admin:change-administrator-password')]
class ChangeAdministratorPasswordCommand extends Command
{
    private AdministratorManager $adminService;

    public function __construct(AdministratorManager $adminService)
    {
        $this->adminService = $adminService;

        parent::__construct();
    }

    public function execute(InputInterface $input, OutputInterface $output): int
    {
        $adminData = $this->askInformations($input, $output);

        if (!$adminData) {
            $output->writeln("<comment>Command Canceled</comment>");
        }

        try {
            $this->adminService->changePassword(
                $adminData['username'],
                $adminData['password']
            );
            $output->writeln('<info>Mot de passe pour ' . $adminData['username'] . ' mis à jour avec succes</info>');
        } catch (Exception $e) {
            $output->writeln("<error>Error: " . $e->getMessage() . "</error>");

            return self::FAILURE;
        }

        return self::SUCCESS;
    }

    private function askInformations(InputInterface $input, OutputInterface $output): bool|array
    {
        $helper = $this->getHelper('question');

        // Username
        $usernameQuestion = new Question('Quel est le nom de l\'administrateur ? ', 'username');

        // Password
        $passwordQuestion = new Question('Quel sera le mot de passe de l\'administrateur ? ', 'not_secret_change_it');
        $passwordQuestion->setHidden(true);

        // Confirmation
        $confirmationQuestion = new ConfirmationQuestion(
            'Êtes-vous sûr de vouloir mettre à jour le mot de passe ? (yes/NO) ', false
        );

        // Ask questions to user
        $username = $helper->ask($input, $output, $usernameQuestion);
        $password = $helper->ask($input, $output, $passwordQuestion);

        // Reformatting values
        $username = strtolower($username);

        // User validate infos
        if (!$helper->ask($input, $output, $confirmationQuestion)) {
            return false;
        }

        // Return statements
        return [
            'username' => strtolower($username),
            'password' => $password,
        ];
    }

    protected function configure(): void
    {
        $this->setDescription('Change password for an existing Admin account.');
    }
}
