<?php

declare(strict_types=1);

namespace App\Framework\ErrorHandling\Handlers;

use App\Framework\Logging\Logger;
use App\Framework\Logging\ValueObjects\LogContext;

/**
 * Fallback handler for all unhandled exceptions
 *
 * Priority: LOWEST - Catches everything that other handlers missed
 */
final readonly class FallbackErrorHandler implements ErrorHandlerInterface
{
    public function __construct(
        private Logger $logger
    ) {}

    public function canHandle(\Throwable $exception): bool
    {
        return true; // Handles everything
    }

    public function handle(\Throwable $exception): HandlerResult
    {
        // Log unhandled exception with full context
        $this->logger->error('Unhandled exception', LogContext::withData([
            'exception_class' => get_class($exception),
            'message' => $exception->getMessage(),
            'file' => $exception->getFile(),
            'line' => $exception->getLine(),
            'trace' => $exception->getTraceAsString()
        ]));

        return HandlerResult::create(
            handled: true,
            message: 'An unexpected error occurred',
            data: [
                'error_type' => 'unhandled',
                'exception_class' => get_class($exception)
            ],
            isFinal: true, // Stop chain - this is the last resort
            statusCode: 500
        );
    }

    public function getName(): string
    {
        return 'fallback_error_handler';
    }

    public function getPriority(): ErrorHandlerPriority
    {
        return ErrorHandlerPriority::LOWEST;
    }
}
