<?php

namespace AutoAdmin\Bundle\Tests\Unit\Seo\EventListener;

use AutoAdmin\Bundle\Seo\EventListener\RedirectEventListener;
use AutoAdmin\Bundle\Seo\Redirect\RedirectService;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;

class RedirectEventListenerTest extends TestCase
{
    public function testNotMainRequest()
    {
        $reflection = new ReflectionClass(RedirectEventListener::class);
        $method = $reflection->getMethod('searchMatchingRedirect');

        $redirectEventListener = $this->getMockBuilder(RedirectEventListener::class)
            ->disableOriginalConstructor()
            ->getMock();

        $event = $this->getMockBuilder(RequestEvent::class)
            ->disableOriginalConstructor()
            ->onlyMethods(['isMainRequest'])
            ->getMock();

        $event->expects($this->once())
            ->method('isMainRequest')
            ->willReturn(false);

        $this->assertNull($method->invokeArgs($redirectEventListener, [$event]));
    }

    public function testMainRequestHasResponse()
    {
        $reflection = new ReflectionClass(RedirectEventListener::class);
        $method = $reflection->getMethod('searchMatchingRedirect');

        $redirectEventListener = $this->getMockBuilder(RedirectEventListener::class)
            ->disableOriginalConstructor()
            ->getMock();

        $redirectService = $this->getMockBuilder(RedirectService::class)
            ->disableOriginalConstructor()
            ->getMock();
        $redirectService->method('getRedirectResponse')->willReturn(new Response());

        $reflection->getProperty('redirectService')->setValue($redirectEventListener, $redirectService);

        $requestEvent = $this->getMockBuilder(RequestEvent::class)
            ->disableOriginalConstructor()
            ->onlyMethods(['isMainRequest', 'setResponse', 'getResponse', 'getRequest'])
            ->getMock();
        $requestEvent->method('getResponse')->willReturn(new Response());

        $requestEvent->expects($this->once())
            ->method('isMainRequest')
            ->willReturn(true);

        $method->invokeArgs($redirectEventListener, [$requestEvent]);

        $this->assertNotNull($requestEvent->getResponse());
    }
}
