<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Command;

use CpCreation\VitiCore\Depot\Model\Depot;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(name: 'viti-core:depot-position')]
class DepotPositionCommand
{
    public function __construct(private EntityManagerInterface $em)
    {
    }

    public function __invoke(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);
        $io->comment('Update Position with postal ASC …');

        $positionNull = $this->em->getRepository(Depot::class)->findOneBy(['position' => null]);
        $depots = $this->em->getRepository(Depot::class)->findAllOrderByCountryOrderByCategoryOrderPostalAll();
        $depots1 = $this->em->getRepository(Depot::class)->findAllOrderByCountryOrderByCategoryOrderPostalAll();

        if ($positionNull) {
            /** @var Depot $depot */
            foreach ($depots as $key => $depot) {
                $depot->setPosition($key);
                $depot->updateTimestampsAtUpdate();
                $this->em->persist($depot);
            }

            $this->em->flush();

            /** @var Depot $depot1 */
            foreach ($depots1 as $key1 => $depot1) {
                $depot1->setPosition($key1);
                $depot1->updateTimestampsAtUpdate();
                $this->em->persist($depot1);
            }

            $this->em->flush();
        }

        return Command::SUCCESS;
    }
}
