<?php

declare(strict_types=1);

namespace Apexl\Io\WhoopsHandlers;

use Apexl\Config\ConfigurationInterface;
use Apexl\Config\Exceptions\MissingConfigException;
use Apexl\Io\Exceptions\JsonRecursionException;
use Apexl\Io\Services\RecursionFinderService;
use Throwable;
use Whoops\Handler\Handler;

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

    /**
     * @throws MissingConfigException
     */
    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;
    }

    /**
     * @throws MissingConfigException
     */
    private function shouldHandleException(Throwable $exception): bool
    {
        return
            $exception instanceof JsonRecursionException &&
            $this->config->get('app.environment') === 'local';
    }
}


