<?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\Logging\Logger;

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

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

        $request = $context->request;

        // Anfrage loggen
        $path = $request->path;
        $method = $request->method;

        // Nächste Middleware aufrufen
        $resultContext = $next($context);

        // Antwort loggen
        $endTime = microtime(true);
        $duration = round(($endTime - $startTime) * 1000, 2);

        // Statuscode nur abrufen, wenn eine Response vorhanden ist
        $status = $resultContext->hasResponse()
            ? $resultContext->response->status->value
            : 'keine Response';

        // Log-Eintrag erstellen
        $logEntry = sprintf(
            '[%s] %s %s - %d (%s ms)',
            date('Y-m-d H:i:s'),
            $method->value,
            $path,
            $status,
            $duration
        );

        $this->logger->info($logEntry);

        // In Log-Datei schreiben...

        return $resultContext;
    }
}
