<?php

namespace App\Command;

use App\Entity\Account;
use App\Service\Generator\TempPasswordGenerator;
use App\Service\Mailer\Event\CreatedAdminEvent;
use Doctrine\ORM\EntityManagerInterface;
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\Question;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Uid\Uuid;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;

#[AsCommand(name: 'ecosplay:admin')]
class AccountCommand extends Command
{
    public function __construct(
        private readonly EventDispatcherInterface $eventDispatcher,
        private readonly UserPasswordHasherInterface $userPasswordHasher,
        private readonly EntityManagerInterface $entityManager,
        ?string $name = null
    ) {
        parent::__construct($name);
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);
        $io->title("Création d'un utilisateur administrateur");



        $existingUser = $this->entityManager->getRepository(Account::class)->findOneBy(['email' => "contact@e-cosplay.fr"]);
        if (!$existingUser instanceof Account) {
            $password = TempPasswordGenerator::generate();
            $newUser = new Account();
            $newUser->setRoles(['ROLE_ROOT']);
            $newUser->setUuid(Uuid::v4());
            $newUser->setIsActif(true);
            $newUser->setIsFirstLogin(true);
            $newUser->setEmail("contact@e-cosplay.fr");
            $newUser->setUsername("Shoko Cosplay");



            $hashedPassword = $this->userPasswordHasher->hashPassword($newUser, $password);
            $newUser->setPassword($hashedPassword);
            $this->eventDispatcher->dispatch(new CreatedAdminEvent($newUser,$password));

            $this->entityManager->persist($newUser);
            $this->entityManager->flush();


            $io->success("Utilisateur administrateur créé avec succès.");
        } else {
            $io->warning("Un utilisateur avec l'email existe déjà.");
        }

        return Command::SUCCESS;
    }
}
