<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;

class LogApiRequest
{
    public function handle(Request $request, Closure $next): Response
    {
        $start    = microtime(true);
        $response = $next($request);
        $duration = round((microtime(true) - $start) * 1000, 2);

        $status = $response->getStatusCode();

        // Logger uniquement si lent (>500ms) ou erreur (4xx/5xx)
        if ($duration > 500 || $status >= 400) {
            Log::channel('api')->info('API Request', [
                'method'      => $request->method(),
                'url'         => $request->fullUrl(),
                'status'      => $status,
                'duration_ms' => $duration,
                'user_id'     => $request->user()?->id,
                'ip'          => $request->ip(),
            ]);
        }

        return $response;
    }
}
