<?php declare(strict_types=1);

namespace Newland\Toubiz\Sync\Neos\Tests\Unit\Importer;

use Neos\Flow\Tests\FunctionalTestCase;
use Newland\Toubiz\Sync\Neos\Domain\Model\Uri;
use Newland\Toubiz\Sync\Neos\Importer\UriImporter;
use Newland\Toubiz\Sync\Neos\Tests\Factory\UriFactory;
use Newland\Toubiz\Sync\Neos\Tests\Unit\Importer\Mock\UriAdapterMock;

class UriImporterTest extends FunctionalTestCase
{
    protected static $testablePersistenceEnabled = true;

    /** @var UriImporter */
    protected $subject;

    public function setUp(): void
    {
        parent::setUp();
        $this->subject = $this->objectManager->get(UriImporter::class);
    }

    public function testImportsUri(): void
    {
        $uri = $this->importAndRefetch([ 'externalId' => '__ID__', 'uri' => 'https://google.com', 'label' => '__LABEL__' ]);
        $this->assertEquals('__ID__', $uri->getOriginalId());
        $this->assertEquals('__LABEL__', $uri->getLabel());
        $this->assertEquals('https://google.com', $uri->getUri());
    }

    public function testReusesExistingUriBasedOnOriginalId(): void
    {
        $existing = (new UriFactory($this->objectManager))->create([ 'originalId' => 'foobar', 'uri' => 'https://before.com' ]);
        $uri = $this->importAndRefetch([ 'externalId' => 'foobar', 'uri' => 'https://after.com' ]);

        $this->assertEquals($existing->getPersistenceObjectIdentifier(), $uri->getPersistenceObjectIdentifier());
    }

    private function importAndRefetch(array $properties): ?Uri
    {
        $uri = $this->subject->import(new UriAdapterMock($properties));
        $this->persistenceManager->persistAll();
        return $this->persistenceManager->getObjectByIdentifier($uri->getPersistenceObjectIdentifier(), Uri::class);
    }

}
