<?php

namespace App\Command;

use App\Entity\User;
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;

/**
 * Administration CLI des comptes (seed / dépannage) :
 *   php bin/console app:user:role <email> <ROLE> [--concessions=A,B] [--status=active]
 */
#[AsCommand(name: 'app:user:role', description: 'Définit le groupe, les concessions et le statut d\'un utilisateur')]
final class UserRoleCommand extends Command
{
    public function __construct(
        private readonly UserRepository $users,
        private readonly EntityManagerInterface $em,
    ) {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this
            ->addArgument('email', InputArgument::REQUIRED, 'Email de l\'utilisateur')
            ->addArgument('role', InputArgument::REQUIRED, 'Groupe : ' . implode(', ', User::GROUPS))
            ->addOption('concessions', null, InputOption::VALUE_REQUIRED, 'Concessions séparées par des virgules')
            ->addOption('status', null, InputOption::VALUE_REQUIRED, 'Statut (active par défaut)', User::STATUS_ACTIVE);
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);
        $email = strtolower(trim((string) $input->getArgument('email')));
        $role = (string) $input->getArgument('role');

        if (!\in_array($role, User::GROUPS, true)) {
            $io->error(sprintf('Groupe invalide. Valeurs : %s', implode(', ', User::GROUPS)));

            return Command::FAILURE;
        }

        $user = $this->users->findOneByEmail($email) ?? new User($email);
        $user->setGroup($role)->setStatus((string) $input->getOption('status'));

        $concessionsOpt = $input->getOption('concessions');
        if (\is_string($concessionsOpt) && '' !== $concessionsOpt) {
            $list = array_values(array_filter(array_map('trim', explode(',', $concessionsOpt))));
            $user->setConcessions($list);
        }
        if (User::STATUS_ACTIVE === $user->getStatus() && null === $user->getValidatedAt()) {
            $user->setValidatedAt(new \DateTimeImmutable())->setValidatedBy('console');
        }

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

        $io->success(sprintf('%s → %s (%s), concessions : %s', $email, User::GROUP_LABELS[$role], $user->getStatus(), $user->getConcessions() ? implode(', ', $user->getConcessions()) : '—'));

        return Command::SUCCESS;
    }
}
