<?php
declare(strict_types=1);

namespace App\Framework\ErrorHandling\View;

use App\Framework\ErrorHandling\ErrorContext;
use App\Framework\ErrorHandling\ExceptionConverter;

/**
 * Renderer für API-Fehler im JSON-Format
 */
final readonly class ApiErrorRenderer implements ErrorViewRendererInterface
{
    /**
     * Rendert einen API-Fehler als JSON
     */
    public function render(ErrorContext $context, bool $isDebug = false): string
    {
        $responseData = [
            'error' => true,
            'message' => $isDebug ? $context->exception->getMessage() : ExceptionConverter::getUserFriendlyMessage($context->exception),
            'requestId' => $context->requestId,
            'timestamp' => $context->additionalData['timestamp'] ?? date('c'),
        ];

        // Im Debug-Modus zusätzliche Informationen hinzufügen
        if ($isDebug) {
            $responseData['details'] = [
                'exception' => get_class($context->exception),
                'file' => $context->exception->getFile(),
                'line' => $context->exception->getLine(),
                'trace' => explode("\n", $context->exception->getTraceAsString()),
                'level' => $context->level->name,
            ];
        }

        return json_encode($responseData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    }
}
