<?php

namespace DigiComp\AssetAttributes\Tests\Functional;

use DigiComp\AssetAttributes\Domain\Model\AssetAttribute;
use Neos\Flow\Persistence\Doctrine\PersistenceManager;
use Neos\Flow\Persistence\Doctrine\Query;
use Neos\Flow\ResourceManagement\ResourceManager;
use Neos\Flow\Tests\FunctionalTestCase;
use Neos\Media\Domain\Model\Asset;

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

    protected ResourceManager $resourceManager;

    protected function setUp(): void
    {
        parent::setUp();
        if (!$this->persistenceManager instanceof PersistenceManager) {
            $this->markTestSkipped('Doctrine persistence is not enabled');
        }
        $this->resourceManager = $this->objectManager->get(ResourceManager::class);
    }

    /**
     * @test
     */
    public function itFindsAssetsHavingAnOwnAttribute(): void
    {
        $resource = $this->resourceManager->importResourceFromContent('hello world', 'hello-world.txt');
        $asset = new Asset($resource);
        $asset->getAttributes()->set('author', new AssetAttribute('author', 'Joe'));
        $this->persistenceManager->add($asset);

        $resource2 = $this->resourceManager->importResourceFromContent('hello universe', 'hello-universe.txt');
        $asset2 = new Asset($resource2);
        $this->persistenceManager->add($asset2);

        $this->persistenceManager->persistAll();

        $query = new Query(Asset::class);
        $result = $query->matching($query->logicalAnd([
            $query->equals('attributes.name', 'author'),
            $query->equals('attributes.value', 'Joe'),
        ]))->execute();
        static::assertCount(1, $result);
    }
}