<?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\Importer\AddressImporter;
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
    {
        $address = $this->factory->create();
        $adapter = new AddressAdapterMock([ 'title' => '__FOO__' ]);

        $this->subject->import($adapter, $address);

        $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, null);

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

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

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

}