<?php

declare(strict_types=1);

namespace App\Command\Migration;

use App\Entity\Client;
use App\Entity\Image;
use App\Entity\ImageRepository;
use App\Entity\OrganizationalUnit;
use App\Model\ImageStatus;
use App\Model\OrganizationalUnitTypes;
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:images', description: 'Migrate images data')]
class MigrateImagesCommand 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');

        $imagesRepository = $this->entityManager->getRepository(Image::class);
        $clientRepository = $this->entityManager->getRepository(Client::class);
        $ouRepository = $this->entityManager->getRepository(OrganizationalUnit::class);

        /** Obtener las imágenes de la base de datos antigua **/
        $rsmOperativeSystems = new ResultSetMapping();
        $rsmOperativeSystems->addScalarResult('idimagen', 'idimagen');
        $rsmOperativeSystems->addScalarResult('nombreca', 'nombreca');
        $rsmOperativeSystems->addScalarResult('idcentro', 'centros.idcentro');
        $rsmOperativeSystems->addScalarResult('idordenador', 'ordenadores.idordenador');
        $rsmOperativeSystems->addScalarResult('numdisk', 'numdisk');
        $rsmOperativeSystems->addScalarResult('ruta', 'ruta');
        $rsmOperativeSystems->addScalarResult('numpar', 'numpar');
        $rsmOperativeSystems->addScalarResult('revision', 'revision');
        $rsmOperativeSystems->addScalarResult('descripcion', 'descripcion');
        $rsmOperativeSystems->addScalarResult('comentarios', 'comentarios');

        $imagesQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idimagen, nombreca, ruta, ordenadores.idordenador, centros.idcentro, numdisk, numpar, revision, descripcion, imagenes.comentarios FROM imagenes LEFT JOIN ordenadores ON imagenes.idordenador = ordenadores.idordenador LEFT JOIN centros ON imagenes.idcentro = imagenes.idcentro', $rsmOperativeSystems);
        $images = $imagesQuery->getResult();

        /** Imágenes **/
        $output->writeln("IMÁGENES TOTAL: ". count($images));

        foreach ($images as $image){
            $ouEntity = $ouRepository->findOneBy(['migrationId' => OrganizationalUnitTypes::ORGANIZATIONAL_UNIT.'-'.$image['centros.idcentro']]);

            if (!$ouEntity) {
                $output->writeln("No se ha encontrado la OU con id: ". $image['centros.idcentro']);
                continue;
            }

            $clientEntity = $clientRepository->findOneBy(['migrationId' => $image['ordenadores.idordenador']]);
            if(!$clientEntity){
                $output->writeln("No se ha encontrado el cliente con id: ". $image['ordenadores.idordenador']);
                continue;
            }

            $imageEntity = $imagesRepository->findOneBy(['migrationId' => $image['idimagen']]);

            $repository = $this->entityManager->getRepository(ImageRepository::class)->findAll()[0];

            if(!$imageEntity) {
                $imageEntity = new Image();
                $imageEntity->setMigrationId((string) $image['idimagen']);
                $imageEntity->setName($image['nombreca']);
                $imageEntity->setClient($clientEntity);
                //$imageEntity->setOrganizationalUnit($ouEntity);
                $imageEntity->setRemotePc(false);
                $imageEntity->setStatus(ImageStatus::SUCCESS);
                $imageEntity->setRepository($repository);
                $imageEntity->setRevision((string) $image['revision']);
                $imageEntity->setDescription($image['descripcion']);
                $imageEntity->setComments($image['comentarios']);
            }

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

        }

        $this->entityManager->flush();

        return Command::SUCCESS;
    }
}
