<?php

namespace App\Tests\EventListener;

use App\EventListener\ExceptionListener;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Twig\Environment;

class ExceptionListenerTest extends TestCase
{
    public function testOnKernelExceptionIgnoreNonProd(): void
    {
        $twig = $this->createStub(Environment::class);
        $listener = new ExceptionListener($twig, 'test');

        $event = $this->createExceptionEvent(new \Exception());
        $listener($event);

        $this->assertNull($event->getResponse());
    }

    public function testOnKernelExceptionProd404(): void
    {
        $twig = $this->createStub(Environment::class);
        $listener = new ExceptionListener($twig, 'prod');

        $exception = new HttpException(404, 'Not Found');
        $twig->method('render')
            ->willReturn('404 content');

        $event = $this->createExceptionEvent($exception);
        $listener($event);

        $response = $event->getResponse();
        $this->assertInstanceOf(Response::class, $response);
        $this->assertSame(404, $response->getStatusCode());
        $this->assertSame('404 content', $response->getContent());
    }

    public function testOnKernelExceptionProd500(): void
    {
        $twig = $this->createStub(Environment::class);
        $listener = new ExceptionListener($twig, 'prod');

        $exception = new \Exception('Global error');
        $twig->method('render')
            ->willReturn('500 content');

        $event = $this->createExceptionEvent($exception);
        $listener($event);

        $response = $event->getResponse();
        $this->assertInstanceOf(Response::class, $response);
        $this->assertSame(500, $response->getStatusCode());
    }

    private function createExceptionEvent(\Throwable $exception): ExceptionEvent
    {
        return new ExceptionEvent(
            $this->createStub(HttpKernelInterface::class),
            new Request(),
            HttpKernelInterface::MAIN_REQUEST,
            $exception
        );
    }
}
