<?php declare(strict_types=1);

namespace Newland\Toubiz\Sync\Neos\Command\MigrationPair;

use Doctrine\ORM\Query;
use Symfony\Component\Console\Output\OutputInterface;

class OriginalIdToExternalId extends MigrationPairFinder
{
    /** @var string */
    protected $toExternalIdType;

    public function __construct(
        OutputInterface $output,
        string $fromSourceSystem,
        string $toSourceSystem,
        string $toExternalIdType
    ) {
        parent::__construct($output, $fromSourceSystem, $toSourceSystem);
        $this->toExternalIdType = $toExternalIdType;
    }

    public function findMigrationPairs(string $language, array $idsToIgnore): \Generator
    {
        $query = $this->articleRepository
            ->createQueryBuilder('article')
            ->select('article.originalId', 'article.Persistence_Object_Identifier');

        $query->where($query->expr()->andX(
            $query->expr()->eq('article.sourceSystem', ':system'),
            $query->expr()->eq('article.language', ':language')
        ));

        $originalIdRows = $query->getQuery()->execute([
            'system' => $this->fromSourceSystem,
            'language' => $language
        ], Query::HYDRATE_ARRAY);

        $message = sprintf(
            '[%s] OriginalId{sourceSystem=%s} ➔ ExternalId{sourceSystem=%s, externalIdType=%s}',
            $language,
            $this->fromSourceSystem,
            $this->toSourceSystem,
            $this->toExternalIdType
        );

        foreach ($this->loopWithBar($originalIdRows, $message) as $row) {
            if ($idsToIgnore[$row['Persistence_Object_Identifier']] ?? false) {
                continue;
            }
            $newId = $this->idByExternalId(
                $this->toSourceSystem,
                $this->toExternalIdType,
                $row['originalId'],
                $language
            );

            if ($newId) {
                yield $row['Persistence_Object_Identifier'] => $newId;
            }
        }
    }
}
