<?php

declare(strict_types=1);

namespace App\Command;

use App\Module\Core\Infrastructure\Doctrine\DoctrineUserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

use function sprintf;

#[AsCommand(
    name: 'app:generate-api-token',
    description: 'Generate or regenerate an API token for a user (used for MCP HTTP authentication)',
)]
class GenerateApiTokenCommand extends Command
{
    public function __construct(
        private readonly DoctrineUserRepository $userRepository,
        private readonly EntityManagerInterface $entityManager,
    ) {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this->addArgument('username', InputArgument::REQUIRED, 'The username to generate a token for');
    }

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

        $user = $this->userRepository->findOneBy(['username' => $username]);

        if (null === $user) {
            $io->error(sprintf('User "%s" not found.', $username));

            return Command::FAILURE;
        }

        $token = bin2hex(random_bytes(32));
        $user->setApiToken($token);
        $this->entityManager->flush();

        $io->success(sprintf('API token generated for user "%s":', $username));
        $io->writeln($token);

        return Command::SUCCESS;
    }
}
