<?php

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\Logging\DefaultLogger;

#[MiddlewarePriorityAttribute(MiddlewarePriority::LOGGING)]
final readonly class LoggingMiddleware implements HttpMiddleware
{
    public function __construct(
        private DefaultLogger $logger
    ) {}

    public function __invoke(MiddlewareContext $context, callable $next, RequestStateManager $stateManager): MiddlewareContext
    {
        $start = microtime(true);

        // Request-Informationen loggen
        $this->logger->info("HTTP Request", [
            'path' => $context->request->path,
            'method' => $context->request->method->value,
            'query' => $context->request->queryParams,
        ]);

        // Nachfolgende Middlewares aufrufen
        $resultContext = $next($context);

        // Dauer berechnen
        $duration = number_format((microtime(true) - $start) * 1000, 2);

        // Status bestimmen
        $status = $resultContext->hasResponse()
            ? $resultContext->response->status->value
            : 'keine Response';

        // Response-Informationen loggen - Warnung bei Fehlercodes
        if ($resultContext->hasResponse() && $resultContext->response->status->value >= 400) {
            $this->logger->warning("HTTP Response", [
                'status' => $status,
                'duration_ms' => $duration,
            ]);
        } else {
            $this->logger->info("HTTP Response", [
                'status' => $status,
                'duration_ms' => $duration,
            ]);
        }

        return $resultContext;
    }
}
