<?php

namespace App\Http\Middleware;

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

class RequestMonitorMiddleware
{
    /**
     * 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);

        $response = $next($request);

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

        // Skip logging for monitoring and log routes to avoid recursion/clutter
        if ($request->is('developer/*') || $request->is('api/developer/*')) {
            return $response;
        }

        try {
            DB::connection('mysql')->table('request_logs')->insert([
                'tenant_id' => $request->user()?->tenant_id ?? null,
                'user_id' => Auth::id(),
                'method' => $request->method(),
                'url' => $request->fullUrl(),
                'ip_address' => $request->ip(),
                'user_agent' => $request->userAgent(),
                'status_code' => $response->getStatusCode(),
                'duration_ms' => $duration,
                'payload' => json_encode($request->except(['password', 'password_confirmation', '_token'])),
                'route_name' => $request->route()?->getName(),
                'controller_action' => $request->route()?->getActionName(),
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        } catch (\Exception $e) {
            // Silently fail to not interrupt the main request flow
            \Log::error('Request monitoring failed: ' . $e->getMessage());
        }

        return $response;
    }
}
