<?php

namespace AutoAdmin\Bundle\Admin\Command\Admin;

use AutoAdmin\Bundle\Admin\Model\AdministratorInterface;
use Doctrine\Persistence\ManagerRegistry;
use Exception;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;

#[AsCommand(name: 'aa:admin:administrator-role-update')]
class AdministratorRoleUpdateCommand extends Command
{
    private ManagerRegistry $doctrine;

    public function __construct(ManagerRegistry $doctrine)
    {
        $this->doctrine = $doctrine;

        parent::__construct();
    }

    protected function configure(): void
    {
        $this->setDescription('Create a new Admin account.');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $outputStyle = new OutputFormatterStyle('red', null);
        $output->getFormatter()->setStyle('error', $outputStyle);

        try {
            $helper = $this->getHelper('question');

            $usernameQuestion = new Question('Username : ', 'username');
            $username = $helper->ask($input, $output, $usernameQuestion);

            $em = $this->doctrine->getManager();
            $adminRepo = $em->getRepository(AdministratorInterface::class);

            /** @var ?AdministratorInterface $admin */
            $admin = $adminRepo->findOneBy(['username' => $username]);

            if (empty($admin)) {
                throw new Exception('Error: No user found with username "' . $username . '"');
            }

            $rolesQuestion = new Question('Roles as uppercase csv as "ROLE_A,ROLE_B": ', 'ROLE_ADMIN');
            $rolesCsv = $helper->ask($input, $output, $rolesQuestion);
            $roles = explode(',', strtoupper($rolesCsv));

            $admin->setRoles($roles);
            $em->persist($admin);
            $em->flush();

        } catch (Exception $e) {
            $output->writeln("<error>Error: " . $e->getMessage() . "</error>");

            return self::FAILURE;
        }

        $output->writeln("<info>The admin '" . $username . "' has been updated with roles '" . $rolesCsv . "'</info>");

        return self::SUCCESS;
    }
}
