<?php

namespace App\Framework\HttpClient\Middleware;

use App\Framework\HttpClient\ClientRequest;
use App\Framework\HttpClient\ClientResponse;
use App\Framework\HttpClient\HttpClientMiddleware;
use App\Framework\Logging\Logger;

final readonly class LoggingMiddleware implements HttpClientMiddleware
{
    public function __construct(
        private Logger $logger
    )
    {
    }

    public function __invoke(ClientRequest $request, callable $next): ClientResponse
    {
        $startTime = microtime(true);

        $this->logger->info('HTTP Request', [
            'method' => $request->method->value,
            'url' => $request->url,
            'headers' => $request->headers->all(),
        ]);

        try {
            $response = $next($request);

            $duration = microtime(true) - $startTime;

            $this->logger->info('HTTP Response', [
                'status' => $response->status->value,
                'duration' => $duration,
                'headers' => $response->headers->all(),
            ]);

            return $response;

        } catch (\Throwable $e) {
            $duration = microtime(true) - $startTime;

            $this->logger->error('HTTP Request Failed', [
                'method' => $request->method->value,
                'url' => $request->url,
                'duration' => $duration,
                'error' => $e->getMessage(),
            ]);

            throw $e;
        }
    }
}
