<?php
declare(strict_types=1);

namespace App\Framework\Http\Middlewares;

use App\Framework\Http\HttpMiddleware;
use App\Framework\Http\MiddlewareContext;
use App\Framework\Http\MiddlewarePriority;
use App\Framework\Http\MiddlewarePriorityAttribute;
use App\Framework\Http\RequestStateManager;
use App\Framework\Http\RequestIdGenerator;
use App\Framework\Http\ResponseManipulator;

/**
 * Middleware zur Verarbeitung von Request-IDs.
 * Generiert eine HMAC-signierte Request-ID und fügt sie als Header hinzu.
 */
#[MiddlewarePriorityAttribute(MiddlewarePriority::VERY_EARLY)]
final readonly class RequestIdMiddleware implements HttpMiddleware
{
    public function __construct(
        private RequestIdGenerator $requestIdGenerator,
        private ResponseManipulator $manipulator
    ) {}

    public function __invoke(MiddlewareContext $context, callable $next, RequestStateManager $stateManager): MiddlewareContext
    {
        // Request-ID generieren/validieren
        $requestId = $this->requestIdGenerator->generate();

        // Request-ID an den weiteren Verarbeitungskontext weitergeben
        $resultContext = $next($context);

        // Request-ID in die Response-Header setzen, falls eine Response vorhanden ist
        if ($resultContext->hasResponse()) {
            $response = $resultContext->response;
            $headers = $response->headers->with(
                $this->requestIdGenerator::getHeaderName(),
                $requestId->toString()
            );
            $updatedResponse = $this->manipulator->withHeaders($response, $headers);

            return $resultContext->withResponse($updatedResponse);
        }

        return $resultContext;
    }
}
