<?php

namespace App\Command;

use App\Entity\ApiKey;
use App\Repository\UserRepository;
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\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(
    name: 'app:api-key:create',
    description: 'Créer une clé API pour un utilisateur',
)]
class ApiKeyCreateCommand extends Command
{
    public function __construct(
        private UserRepository $userRepository,
        private EntityManagerInterface $entityManager
    ) {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this
            ->addArgument('pseudo', InputArgument::REQUIRED, 'Le pseudo de l\'utilisateur')
            ->addArgument('name', InputArgument::REQUIRED, 'Le nom de la clé API')
            ->addOption('expires', null, InputOption::VALUE_OPTIONAL, 'Date d\'expiration (format Y-m-d H:i:s)', null);
    }

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

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

        if (!$user) {
            $io->error("Utilisateur '$pseudo' non trouvé");
            return Command::FAILURE;
        }

        $apiKey = new ApiKey();
        $apiKey->setName($name);
        $apiKey->setUser($user);

        if ($expires) {
            try {
                $apiKey->setExpiresAt(new \DateTime($expires));
            } catch (\Exception $e) {
                $io->error("Format de date invalide: {$e->getMessage()}");
                return Command::FAILURE;
            }
        }

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

        $io->success("Clé API créée avec succès!");
        $io->text([
            "Utilisateur: {$user->getPseudo()}",
            "Nom: {$apiKey->getName()}",
            "Token: {$apiKey->getToken()}",
            "Créée à: {$apiKey->getCreatedAt()->format('Y-m-d H:i:s')}",
            $expires ? "Expire à: {$apiKey->getExpiresAt()->format('Y-m-d H:i:s')}" : '',
        ]);

        return Command::SUCCESS;
    }
}

