<?php

namespace App\EventListener;

use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Twig\Environment;

#[AsEventListener(event: KernelEvents::EXCEPTION)]
class ExceptionListener
{
    public function __construct(
        private readonly Environment $twig,
        #[Autowire('%kernel.environment%')] private readonly string $kernelEnvironment,
    ) {
    }

    public function __invoke(ExceptionEvent $event): void
    {
        if ('prod' !== $this->kernelEnvironment) {
            return;
        }

        $exception = $event->getThrowable();
        $statusCode = $exception instanceof HttpExceptionInterface ? $exception->getStatusCode() : 500;

        if (404 === $statusCode) {
            $template = 'error/404.html.twig';
        } else {
            $template = 'error/500.html.twig';
        }

        $response = new Response(
            $this->twig->render($template, [
                'status_code' => $statusCode,
                'error_message' => $exception->getMessage(),
            ]),
            $statusCode,
        );

        if ($exception instanceof HttpExceptionInterface) {
            $response->headers->add($exception->getHeaders());
        }

        $event->setResponse($response);
    }
}
