<?php

namespace App\Http\Middleware;

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

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

        $user = Auth::user();
        $userRoles = $user ? $user->roles->pluck('title')->implode(', ') : 'guest';

        Log::create([
            'user_id'      => $user->id,
            'role'         => $userRoles,
            'action'       => $request->method(),
            'description'  => "Accessed: " . $request->path(),
            'ip_address'   => $user->ip_address,
        ]);

        return $response;
    }
}
