<?php


namespace App\Command;

use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ChoiceQuestion;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;

#[AsCommand(
    name: 'mto:agent:user:create',
    description: 'Creates a new admin user'
)]
class CreateUserCommand extends Command
{
    public function __construct(
        private EntityManagerInterface      $em,
        private UserPasswordHasherInterface $passwordHasher
    )
    {
        parent::__construct();
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        /** @var QuestionHelper $helper */
        $helper = $this->getHelper('question');

        // =============================
        // Email
        // =============================
        $emailQuestion = new Question('E-Mail: ');
        $emailQuestion->setValidator(function ($value) {
            if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
                throw new \RuntimeException('Invalid email address.');
            }
            return strtolower(trim($value));
        });

        $email = $helper->ask($input, $output, $emailQuestion);

        // Prüfen ob User existiert
        $existingUser = $this->em
            ->getRepository(User::class)
            ->findOneBy(['email' => $email]);

        if ($existingUser) {
            $output->writeln('<error>User already exists.</error>');
            return Command::FAILURE;
        }

        // =============================
        // Passwort
        // =============================
        $passwordQuestion = new Question('Password: ');
        $passwordQuestion->setHidden(true);
        $passwordQuestion->setHiddenFallback(false);

        $plainPassword = $helper->ask($input, $output, $passwordQuestion);

        if (strlen($plainPassword) < 8) {
            $output->writeln('<error>Password must be at least 8 characters.</error>');
            return Command::FAILURE;
        }

        // =============================
        // Rolle auswählen
        // =============================
        $roleQuestion = new ChoiceQuestion(
            'Select role:',
            [
                'ROLE_SUPER_ADMIN',
                'ROLE_KNOWLEDGE_ADMIN',
                'ROLE_EDITOR',
                'ROLE_USER',
            ],
            0
        );

        $role = $helper->ask($input, $output, $roleQuestion);

        // =============================
        // User erzeugen
        // =============================
        $user = new User();
        $user->setEmail($email);
        $user->setRoles([$role]);

        $hashedPassword = $this->passwordHasher->hashPassword($user, $plainPassword);
        $user->setPassword($hashedPassword);

        $this->em->persist($user);
        $this->em->flush();

        $output->writeln('<info>User created successfully.</info>');
        $output->writeln('Email: ' . $email);
        $output->writeln('Role: ' . $role);

        return Command::SUCCESS;
    }
}
