<?php

namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CheckSessionLimit
{
    public function handle($request, Closure $next)
    {
        if (User::check()) {
            $sessions = User::user()->tokens()->where('revoked', false)->count();

            if ($sessions > 1) {
                // Cierra sesión en las sesiones adicionales
                User::user()->tokens()->where('revoked', false)->skip(1)->take($sessions - 1)->update(['revoked' => true]);
            }
        }

        return $next($request);
    }
}
