<?php

namespace App\Tests\EventSubscriber;

use App\EventSubscriber\DisableProfilerSubscriber;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Profiler\Profiler;

class DisableProfilerSubscriberTest extends TestCase
{
    public function testSubscribedEvents(): void
    {
        $events = DisableProfilerSubscriber::getSubscribedEvents();

        self::assertArrayHasKey(KernelEvents::RESPONSE, $events);
    }

    public function testDisablesProfilerOnBilletPreviewRoute(): void
    {
        $profiler = $this->createMock(Profiler::class);
        $profiler->expects(self::once())->method('disable');

        $subscriber = new DisableProfilerSubscriber($profiler);

        $request = new Request();
        $request->attributes->set('_route', 'app_account_event_billet_preview');

        $kernel = $this->createMock(HttpKernelInterface::class);
        $event = new ResponseEvent($kernel, $request, HttpKernelInterface::MAIN_REQUEST, new Response());

        $subscriber->onKernelResponse($event);
    }

    public function testDoesNotDisableProfilerOnOtherRoutes(): void
    {
        $profiler = $this->createMock(Profiler::class);
        $profiler->expects(self::never())->method('disable');

        $subscriber = new DisableProfilerSubscriber($profiler);

        $request = new Request();
        $request->attributes->set('_route', 'app_home');

        $kernel = $this->createMock(HttpKernelInterface::class);
        $event = new ResponseEvent($kernel, $request, HttpKernelInterface::MAIN_REQUEST, new Response());

        $subscriber->onKernelResponse($event);
    }

    public function testHandlesNullProfiler(): void
    {
        $subscriber = new DisableProfilerSubscriber(null);

        $request = new Request();
        $request->attributes->set('_route', 'app_account_event_billet_preview');

        $kernel = $this->createMock(HttpKernelInterface::class);
        $event = new ResponseEvent($kernel, $request, HttpKernelInterface::MAIN_REQUEST, new Response());

        // No exception thrown
        $subscriber->onKernelResponse($event);
        self::assertTrue(true);
    }

    public function testIgnoresSubRequests(): void
    {
        $profiler = $this->createMock(Profiler::class);
        $profiler->expects(self::never())->method('disable');

        $subscriber = new DisableProfilerSubscriber($profiler);

        $request = new Request();
        $request->attributes->set('_route', 'app_account_event_billet_preview');

        $kernel = $this->createMock(HttpKernelInterface::class);
        $event = new ResponseEvent($kernel, $request, HttpKernelInterface::SUB_REQUEST, new Response());

        $subscriber->onKernelResponse($event);
    }
}
