<?php

// 2. Middleware for automatic presence tracking

namespace App\Http\Middleware;

use App\Services\PresenceService;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class TrackUserPresence
{
    protected $presenceService;

    public function __construct(PresenceService $presenceService)
    {
        $this->presenceService = $presenceService;
    }

    public function handle(Request $request, Closure $next, $guard = null)
    {
        // If no guard specified, use the active guard from session (defaults to 'web')
        // This ensures we only track presence for the currently active profile
        $activeGuard = $guard ?? $request->session()->get('active_guard', 'web');

        if (auth($activeGuard)->check()) {
            $user = auth($activeGuard)->user();
            $cacheKey = "presence_last_update_{$activeGuard}_{$user->id}";
            $lastUpdate = Cache::get($cacheKey);

            if (!$lastUpdate || now()->diffInSeconds($lastUpdate) >  timebank_config('presence_settings.update_interval', 60)) { // Only update using this  interval
                $this->presenceService->updatePresence($user, $activeGuard);
                Cache::put($cacheKey, now(), 300);
            }
        }

        return $next($request);
    }
}
