<?php

declare(strict_types=1);

namespace App\Framework\ErrorAggregation;

use App\Framework\Exception\ErrorHandlerContext;
use App\Framework\Http\HttpMiddleware;
use App\Framework\Http\MiddlewareContext;
use App\Framework\Http\Next;
use App\Framework\Http\RequestStateManager;
use Throwable;

/**
 * Middleware that captures errors for aggregation
 */
final readonly class ErrorAggregationMiddleware implements HttpMiddleware
{
    public function __construct(
        private ErrorAggregator $errorAggregator,
        private bool $enabled = true
    ) {
    }

    public function __invoke(MiddlewareContext $context, Next $next, RequestStateManager $stateManager): MiddlewareContext
    {
        if (! $this->enabled) {
            return $next($context);
        }

        try {
            return $next($context);
        } catch (Throwable $e) {
            // If we have an ErrorHandlerContext available, aggregate the error
            $errorHandlerContext = $stateManager->get('error_handler_context');

            if ($errorHandlerContext instanceof ErrorHandlerContext) {
                try {
                    $this->errorAggregator->processError($errorHandlerContext);
                } catch (Throwable $aggregateException) {
                    // Don't let aggregation errors break the application
                    // Could log this separately if needed
                }
            }

            // Re-throw the original exception
            throw $e;
        }
    }
}
