<?php

namespace App\EventListener;

use ApiPlatform\Exception\ItemNotFoundException;
use ApiPlatform\Symfony\Validator\Exception\ValidationException;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Exception\BadRequestException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use ApiPlatform\Exception\FilterValidationException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;

class ExceptionListener
{
    public function __construct(private LoggerInterface $logger)
    {
    }

    public function onKernelException(ExceptionEvent $event): void
    {
        //        $exception = $event->getThrowable();
        //
        //        $response = match(true) {
        //            $exception instanceof FilterValidationException,
        //                $exception instanceof BadRequestException => $this->createResponse($exception, Response::HTTP_BAD_REQUEST),
        //            $exception instanceof NotFoundHttpException,
        //                $exception instanceof ItemNotFoundException => $this->createResponse($exception, Response::HTTP_NOT_FOUND),
        //            $exception instanceof AccessDeniedHttpException => $this->createResponse($exception, Response::HTTP_FORBIDDEN),
        //            $exception instanceof ValidationException,
        //                $exception instanceof NotNormalizableValueException => $this->createResponse($exception, Response::HTTP_UNPROCESSABLE_ENTITY),
        //            default => null,
        //        };
        //
        //        if ($response) {
        //            $event->setResponse($response);
        //        }else{
        //            $this->logger->error($exception->getMessage(), ['exception' => $exception]);
        //        }
    }

    private function createResponse(\Throwable $exception, int $statusCode): Response
    {
        $this->logger->info($exception->getMessage(), ['exception' => $exception]);
        return new Response(json_encode(['message' => $exception->getMessage()]), $statusCode, ['Content-Type' => 'application/json']);
    }
}
