<?php

namespace App\Command;

use App\Entity\Equipement;
use App\Service\EquipementManager;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

/**
 * Commande pour initialiser le flag a_servir pour tous les équipements existants
 */
class InitAServirFlagCommand extends Command
{
    protected static $defaultName = 'app:init-a-servir-flag';

    private EntityManagerInterface $entityManager;
    private EquipementManager $equipementManager;

    public function __construct(EntityManagerInterface $em, EquipementManager $equipementManager)
    {
        parent::__construct();
        $this->entityManager = $em;
        $this->equipementManager = $equipementManager;
    }

    protected function configure(): void
    {
        $this
            ->setDescription('Initialise le flag a_servir pour tous les équipements existants');
    }

    protected function initialize(InputInterface $input, OutputInterface $output): void
    {
        // Augmenter la limite de mémoire pour traiter beaucoup d'équipements
        ini_set('memory_limit', '-1');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);
        $io->title('Initialisation du flag a_servir');

        // Récupérer tous les équipements
        $equipements = $this->entityManager->getRepository(Equipement::class)->findAll();
        $total = count($equipements);
        
        $io->progressStart($total);
        $io->info("Traitement de {$total} équipements...");

        $updated = 0;
        $batchSize = 100;
        $batchCount = 0;

        foreach ($equipements as $equipement) {
            // Calculer et mettre à jour le flag
            $this->equipementManager->updateAServirFlag($equipement);
            
            $updated++;
            $batchCount++;

            // Flush par batch pour optimiser les performances
            if ($batchCount >= $batchSize) {
                $this->entityManager->flush();
                $batchCount = 0;
            }

            $io->progressAdvance();
        }

        // Flush final
        if ($batchCount > 0) {
            $this->entityManager->flush();
        }

        $io->progressFinish();
        $io->success("Initialisation terminée : {$updated} équipements traités");

        return Command::SUCCESS;
    }
}

