<?php

namespace DMD\LaLigaApi\Exception;

use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Exception\ORMException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use DMD\LaLigaApi\Entity\Log;

class ExceptionListener
{
    public function __construct(public EntityManagerInterface $entityManager){}

    public function onKernelException(ExceptionEvent $event): void
    {
        $exception = $event->getThrowable();
        $log = new Log();
        $log->setPayload($event->getRequest()->getContent());
        if ($exception instanceof HttpExceptionInterface)
        {
            $log->setCode($exception->getStatusCode());
            $log->setMessage($exception->getMessage());
            $response = new JsonResponse([
                'success' => false,
                'error' => [
                    'code' => $exception->getStatusCode(),
                    'message' => $exception->getMessage()
                ]
            ]);
            $response->headers->set('Content-Type', 'application/json');
            $response->setStatusCode($exception->getStatusCode());
        }
        elseif($exception instanceof ValidationException)
        {
            $response = new JsonResponse(
                data: [
                    'success' => false,
                    'error' => [
                        'code' => $exception->getCode(),
                        'message' => 'Validation errors',
                        'validationErrors' => $exception->getValidationErrors()
                    ]
                ],
                status: $exception->getCode()
            );
        }
        else
        {
            $log->setCode(Response::HTTP_INTERNAL_SERVER_ERROR);
            $log->setMessage($exception->getMessage());
            $response = new JsonResponse([
                'error'=> [
                    'code' => Response::HTTP_INTERNAL_SERVER_ERROR,
                    'message' => $exception->getMessage()
                ]
            ]);
            $response->headers->set('Content-Type', 'application/json');
            $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
        }
        if (!($exception instanceof ORMException))
        {
            $this->entityManager->persist($log);
            $this->entityManager->flush();
            $this->entityManager->clear();
        }
        $event->setResponse($response);
        $event->allowCustomResponseCode();
    }
}
