<?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\Address;
use Newland\Toubiz\Sync\Neos\Domain\Repository\AddressRepository;
use Newland\Toubiz\Sync\Neos\Importer\AddressImporter;
use Newland\Toubiz\Sync\Neos\Orm\Uuid\UuidGenerator;
use Newland\Toubiz\Sync\Neos\Tests\Factory\AddressFactory;
use Newland\Toubiz\Sync\Neos\Tests\Unit\Importer\Mock\AddressAdapterMock;

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

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

    /** @var AddressFactory */
    protected $factory;

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

    public function testReusesGivenModel(): void
    {
        /** @var Address $address */
        $address = $this->factory->create(
            [
                'originalId' => 'original-id-123',
            ]
        );

        $adapter = new AddressAdapterMock(
            [
                'title' => '__FOO__',
                'externalId' => 'original-id-123',
            ]
        );

        $test = $this->subject->import($adapter);

        $fromDb = $this->persistenceManager->getObjectByIdentifier(
            $address->getPersistenceObjectIdentifier(),
            Address::class
        );
        $this->assertNotNull($fromDb);
        $this->assertEquals('__FOO__', $fromDb->getName());
        $this->assertEquals('__FOO__', $address->getName());
    }


    public function testCreatesNewAddressIfNoneGiven(): void
    {
        $adapter = new AddressAdapterMock([ 'title' => '__BAR__' ]);
        $imported = $this->subject->import($adapter);

        $fromDb = $this->persistenceManager->getObjectByIdentifier(
            $imported->getPersistenceObjectIdentifier(),
            Address::class
        );
        $this->assertNotNull($fromDb);
        $this->assertEquals('__BAR__', $fromDb->getName());
    }

    public function testTwoAddressesWithSameExternalIdAreNotOverwritten(): void
    {
        $this->subject->setLanguage('de');
        $one = $this->subject->import(new AddressAdapterMock(['externalId' => 'test' ]));

        $this->persistenceManager->persistAll();

        $two = $this->subject->import(new AddressAdapterMock(['externalId' => 'test' ]));

        $this->assertNotNull($one);
        $this->assertNotNull($two);
        $this->assertEquals($one->getPersistenceObjectIdentifier(), $two->getPersistenceObjectIdentifier());
    }
}
