<?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\File;
use Newland\Toubiz\Sync\Neos\Importer\FileImporter;
use Newland\Toubiz\Sync\Neos\Tests\Factory\FileFactory;
use Newland\Toubiz\Sync\Neos\Tests\Unit\Importer\Mock\FileAdapterMock;

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

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

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

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

    public function testReusesGivenModel(): void
    {
        $file = $this->factory->create();
        $adapter = new FileAdapterMock([ 'name' => '__FOO__' ]);

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

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

    public function testCreatesNewAddressIfNoneGiven(): void
    {
        $adapter = new FileAdapterMock([ 'name' => '__BAR__' ]);
        $imported = $this->subject->import($adapter, null);

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

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

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


}