<?php declare(strict_types=1);

namespace Newland\Toubiz\Services\Neos\Tests\Unit\Search;

use Neos\Flow\Tests\FunctionalTestCase;
use Newland\Toubiz\Search\Neos\Progress\NullHandler;
use Newland\Toubiz\Search\Neos\Tests\Mock\SearchBackendMock;
use Newland\Toubiz\Services\Neos\Search\ServiceIndexer;
use Newland\Toubiz\Sync\Neos\Tests\Factory\ServiceFactory;

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

    /**
     * @var ServiceFactory
     */
    protected $serviceFactory;

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

    public function setUp(): void
    {
        parent::setUp();
        $this->subject = $this->objectManager->get(ServiceIndexer::class);
        $this->serviceFactory = new ServiceFactory($this->objectManager);
    }

    public function testIndexesService(): void
    {
        $this->serviceFactory->create(
            [
                'name' => '__NAME__',
                'benefits' => [ '__SUPER_COOL_BENEFIT__' ],
            ]
        );

        $backend = new SearchBackendMock();
        $this->subject->index(['/sites/foo'], $backend, new NullHandler());

        $this->assertCount(1, $backend->modifications);
        $this->assertEquals('__NAME__', $backend->modifications[0]->getTitle());
        $this->assertContains('__SUPER_COOL_BENEFIT__', $backend->modifications[0]->getContent());
    }

    public function testIndexesAllServices(): void
    {
        $this->serviceFactory->createMultiple(25);
        $backend = new SearchBackendMock();
        $this->subject->index(['/sites/foo'], $backend, new NullHandler());
        $this->assertCount(25, $backend->modifications);
    }

    public function testMemorizesIndexedIdsForDeletionLaterOn(): void
    {
        $services = $this->serviceFactory->createMultiple(5);

        $backend = new SearchBackendMock();
        $this->subject->index(['/sites/foo'], $backend, new NullHandler());
        $this->subject->postIndex($backend);

        $this->assertCount(1, $backend->identifiersToRetainWhenDeleting);
        $this->assertCount(5, $backend->identifiersToRetainWhenDeleting[0]);
        foreach ($services as $service) {
            $this->assertContains(
                $service->getPersistenceObjectIdentifier(),
                $backend->identifiersToRetainWhenDeleting[0]
            );
        }
    }
}
