<?php

namespace App\Command\Migration;

use App\Entity\Client;
use App\Entity\HardwareProfile;
use App\Entity\OperativeSystem;
use App\Entity\OrganizationalUnit;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Query\ResultSetMapping;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(name: 'opengnsys:migration:os', description: 'Migrate os data')]
class MigrateOperativeSystemCommand extends Command
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private readonly ManagerRegistry $doctrine
    )
    {
        parent::__construct();
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        /** @var EntityManagerInterface $oldDatabaseEntityManager */
        $oldDatabaseEntityManager = $this->doctrine->getManager('og_1');

        $osRepository = $this->entityManager->getRepository(OperativeSystem::class);

        /** Obtener los sistemas operativos de la base de datos antigua **/
        $rsmOperativeSystems = new ResultSetMapping();
        $rsmOperativeSystems->addScalarResult('idnombreso', 'idnombreso');
        $rsmOperativeSystems->addScalarResult('nombreso', 'nombreso');

        $operativeSystemQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idnombreso, nombreso FROM nombresos', $rsmOperativeSystems);
        $opeativeSystems = $operativeSystemQuery->getResult();

        /** Sistemas operativos **/
        $output->writeln("SISTEMAS OPERATIVOS TOTAL: ". count($opeativeSystems));
        foreach ($opeativeSystems as $client){
            $osEntity = $osRepository->findOneBy(['migrationId' => $client['idnombreso']]);
            if(!$osEntity) {
                $osEntity = new OperativeSystem();
                $osEntity->setMigrationId($client['idnombreso']);
                $osEntity->setName($client['nombreso']);
            }

            $this->entityManager->persist($osEntity);
        }
        $this->entityManager->flush();

        return Command::SUCCESS;
    }
}