<?php declare(strict_types=1);

namespace Newland\Toubiz\Sync\Neos\Tests\Unit\Service;

use Neos\Flow\Tests\FunctionalTestCase;
use Newland\Toubiz\Sync\Neos\Service\UrlIdentifierRedirectService;

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

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

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

    public function testReturnsOnlyOriginIdIfNoRecordExists(): void
    {
        $this->assertEquals([ 'foo' ], $this->subject->getRedirects('foo'));
    }

    public function testSavesDestinationId(): void
    {
        $this->subject->addRedirect('foo', 'bar');
        $this->assertContains('bar', $this->subject->getRedirects('foo'));
    }

    public function testSavesMultipleDestinationIds(): void
    {
        $this->subject->addRedirect('foo', 'bar');
        $this->subject->addRedirect('foo', 'baz');
        $this->assertContains('bar', $this->subject->getRedirects('foo'));
        $this->assertContains('baz', $this->subject->getRedirects('foo'));
    }

    public function testDoesNotSaveSamePairTwice(): void
    {
        $this->subject->addRedirect('foo', 'bar');
        $this->subject->addRedirect('foo', 'bar');

        $redirects = $this->subject->getRedirects('foo');
        $barRedirects = array_filter($redirects, function($redirect) {
            return $redirect === 'bar';
        });

        $this->assertCount(1, $barRedirects);
    }

    public function testPrependsSourceId(): void
    {
        $this->subject->addRedirect('foo', 'bar');
        $this->assertEquals('foo', $this->subject->getRedirects('foo')[0]);
    }
}
