<?php

namespace App\Http\Middleware;

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

class RequestLoggingMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $startTime = microtime(true);

        // Log the incoming request
        $this->logRequest($request);

        $response = $next($request);

        // Log the response
        $this->logResponse($request, $response, $startTime);

        return $response;
    }

    /**
     * Log incoming request details
     */
    protected function logRequest(Request $request): void
    {
        $context = [
            'method' => $request->method(),
            'url' => $request->fullUrl(),
            'ip' => $request->ip(),
            'user_agent' => $request->userAgent(),
            'user_id' => auth()->id(),
            'user_name' => auth()->user()->name ?? 'Guest',
            'request_id' => uniqid(),
        ];

        // Log sensitive operations
        if (in_array($request->method(), ['POST', 'PUT', 'PATCH', 'DELETE'])) {
            Log::channel('security')->info('Sensitive operation detected', $context);
        }

        // Log authentication attempts
        if ($request->is('login') || $request->is('logout')) {
            Log::channel('security')->info('Authentication attempt', $context);
        }
    }

    /**
     * Log response details
     */
    protected function logResponse(Request $request, Response $response, float $startTime): void
    {
        $duration = (microtime(true) - $startTime) * 1000; // Convert to milliseconds

        $context = [
            'method' => $request->method(),
            'url' => $request->fullUrl(),
            'status_code' => $response->getStatusCode(),
            'duration_ms' => round($duration, 2),
            'user_id' => auth()->id(),
            'user_name' => auth()->user()->name ?? 'Guest',
        ];

        // Log slow requests
        if ($duration > 1000) { // More than 1 second
            Log::channel('application')->warning('Slow request detected', $context);
        }

        // Log error responses
        if ($response->getStatusCode() >= 400) {
            Log::channel('error_email')->error('HTTP error response', $context);
        }
    }
}
