<?php
namespace Crawl\Lib;

class ErrorHandler
{
    public static function register(): void
    {
        set_exception_handler(function (\Throwable $e): void {
            $debug = filter_var($_ENV['APP_DEBUG'] ?? false, FILTER_VALIDATE_BOOL);
            if (self::isApiRequest()) {
                Response::error($debug ? $e->getMessage() : 'Internal server error', 500);
            }

            http_response_code(500);
            echo $debug ? '<pre>' . htmlspecialchars($e->getMessage() . "\n" . $e->getTraceAsString()) . '</pre>' : 'Internal server error';
        });
    }

    private static function isApiRequest(): bool
    {
        $uri = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?? '/';
        return strpos($uri, '/api/') !== false;
    }
}
