<?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\Next;
use App\Framework\Http\RequestStateManager;
use App\Framework\Http\ResponseManipulator;

#[MiddlewarePriorityAttribute(MiddlewarePriority::SECURITY)]
final readonly class RemovePoweredByMiddleware implements HttpMiddleware
{
    public function __construct(
        private ResponseManipulator $manipulator
    ) {
    }

    public function __invoke(MiddlewareContext $context, Next $next, RequestStateManager $stateManager): MiddlewareContext
    {
        // Nächste Middleware aufrufen
        $resultContext = $next($context);


        // Wenn eine Response vorhanden ist, X-Powered-By Header entfernen
        if ($resultContext->hasResponse()) {

            $response = $resultContext->response;
            $updatedHeaders = $response->headers;

            // X-Powered-By Header entfernen, falls vorhanden
            if ($updatedHeaders->has('X-Powered-By')) {
                $updatedHeaders = $updatedHeaders->without('X-Powered-By');

                // Neue Response mit aktualisierten Headers erstellen
                $updatedResponse = $this->manipulator->withHeaders($response, $updatedHeaders);


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

        return $resultContext;
    }
}
