<?php declare(strict_types=1);

namespace Newland\Toubiz\Poi\Neos\Tests\Unit\LinkHandler\Eel\Helper;

use Neos\ContentRepository\Domain\Model\Node;
use Neos\Flow\Tests\FunctionalTestCase;
use Newland\NeosTestingHelpers\CompilesFusion;
use Newland\NeosTestingHelpers\InteractsWithNodes;
use Newland\Toubiz\Sync\Neos\Domain\Model\Article;
use Newland\Toubiz\Sync\Neos\Tests\Factory\ArticleFactory;

class ArticleHelperTest extends FunctionalTestCase
{
    use InteractsWithNodes, CompilesFusion;
    protected static $testablePersistenceEnabled = true;

    /** @var Node */
    protected $node;

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

    public function setUp(): void
    {
        parent::setUp();

        $site = $this->initializeSite('foo');
        $this->node = $this->initializeNode('/sites/foo', null, $site);
        $this->factory = new ArticleFactory($this->objectManager);
    }

    public function testDoesNotFailIfNothingGiven(): void
    {
        $result = $this->compileFusion($this->node, '${Newland.Toubiz.Article.findByIdentifier(q(node).property("article"))}');
        $this->assertNull($result);
    }

    public function testFindsArticleByIdentifier(): void
    {
        $article = $this->factory->create([ ]);
        $this->node->setProperty('article', $article->getPersistenceObjectIdentifier());
        $this->persistNode($this->node);

        $result = $this->compileFusion($this->node, '${Newland.Toubiz.Article.findByIdentifier(q(node).property("article"))}');
        $this->assertInstanceOf(Article::class, $result);
    }

    public function testFindsArticlesByIdentifier(): void
    {
        [ $one, $two, $three ] = $this->factory->createMultiple(3);
        $this->node->setProperty(
            'articles',
            [ $one->getPersistenceObjectIdentifier(), $two->getPersistenceObjectIdentifier(), $three->getPersistenceObjectIdentifier() ]
        );
        $this->persistNode($this->node);

        $result = $this->compileFusion($this->node, '${Newland.Toubiz.Article.findByIdentifiers(q(node).property("articles"))}');

        $this->assertIsArray($result);
        $this->assertCount(3, $result);
        $this->assertInstanceOf(Article::class, $result[0]);
        $this->assertInstanceOf(Article::class, $result[1]);
        $this->assertInstanceOf(Article::class, $result[2]);
    }
}
