<?php

declare(strict_types=1);

namespace apexl\Io\WhoopsHandlers;

use apexl\Io\exceptions\JsonRecursionException;
use apexl\Io\services\RecursionFinderService;
use Throwable;
use Whoops\Handler\Handler;
use function apexl\Io\config;

final class JsonRecursionErrorHandler extends Handler
{
    public function __construct(private readonly RecursionFinderService $recursionFinder) {}

    public function handle(): ?int
    {
        $exception = $this->getInspector()->getException();
        if ($this->shouldHandleException($exception)) {
            /** @var JsonRecursionException $exception */
            $data = ['error' => $exception->getMessage()];
            $data['recursion'] = $this->recursionFinder->find($exception->data);
            echo json_encode($data, JSON_PRETTY_PRINT & JSON_PARTIAL_OUTPUT_ON_ERROR);

            return Handler::QUIT;
        };

        return null;
    }

    private function shouldHandleException(Throwable $exception): bool
    {
        return
            $exception instanceof JsonRecursionException &&
            config('app.environment') === 'local';
    }
}


