<?php

declare(strict_types=1);

namespace Core\Framework\Event\Listener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

readonly class ResponseListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::RESPONSE => ['onKernelResponse'],
        ];
    }

    /**
     * @throws \JsonException
     */
    public function onKernelResponse(ResponseEvent $event): void
    {
        $response = $event->getResponse();

        switch (true) {
            case $response->getStatusCode() === Response::HTTP_UNPROCESSABLE_ENTITY:
                $this->onValidationErrorResponse($response);
                break;
            default:
        }
    }

    /**
     * @throws \JsonException
     */
    private function onValidationErrorResponse(Response $response): void
    {
        if (!$response instanceof JsonResponse || !\is_string($response->getContent())) {
            return;
        }

        $content = json_decode($response->getContent(), true, 512, \JSON_THROW_ON_ERROR);

        $response->setJson(json_encode($content, \JSON_FORCE_OBJECT | \JSON_THROW_ON_ERROR));
    }
}
