<?php

namespace App\Console\Commands;

use App\Services\PresenceService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Spatie\Activitylog\Models\Activity;

class CleanupOfflineUsers extends Command
{
    protected $signature = 'presence:cleanup-offline {--minutes=5}';
    protected $description = 'Mark inactive users as offline';

    public function handle()
    {
        $minutes = $this->option('minutes');
        $presenceService = app(PresenceService::class);

        // Find users who haven't been active
        $inactiveUsers = Activity::where('log_name', PresenceService::PRESENCE_ACTIVITY)
            ->where('created_at', '<', now()->subMinutes($minutes))
            ->where('properties->status', '!=', 'offline')
            ->with('subject')
            ->get()
            ->unique('subject_id');

        $count = 0;
        foreach ($inactiveUsers as $activity) {
            if ($activity->subject) {
                $guard = $activity->properties['guard'] ?? 'web';
                $presenceService->setUserOffline($activity->subject, $guard);
                $count++;
            }
        }

        // Clear all presence caches
        $guards = ['web', 'admin']; // Add your guards here
        foreach ($guards as $guard) {
            Cache::forget("online_users_{$guard}_5");
        }

        $this->info("Marked {$count} inactive users as offline.");
        return 0;
    }
}
