<?php

declare(strict_types=1);

namespace App\Framework\Http\Middlewares;

use App\Framework\Http\Headers;
use App\Framework\Http\HttpMiddleware;
use App\Framework\Http\HttpResponse;
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\Status;

/**
 * Terminal middleware that ensures every request gets a response.
 *
 * This middleware should be placed at the end of the middleware chain
 * to catch any requests that haven't received a response from previous
 * middlewares and provide a sensible default (404 Not Found).
 */
#[MiddlewarePriorityAttribute(MiddlewarePriority::FALLBACK)]
final readonly class DefaultResponseMiddleware implements HttpMiddleware
{
    public function __invoke(MiddlewareContext $context, Next $next, RequestStateManager $stateManager): MiddlewareContext
    {
        $resultContext = $next($context);

        if (! $resultContext->hasResponse()) {
            $response = new HttpResponse(
                status: Status::NOT_FOUND,
                headers: new Headers([
                    'Content-Type' => 'text/plain; charset=utf-8',
                ]),
                body: 'Not Found'
            );

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

        return $resultContext;
    }
}
