<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\UserSession;
use Carbon\Carbon;

class CleanExpiredSessions extends Command
{
    protected $signature = 'sessions:clean';
    protected $description = 'Clean expired user sessions by setting logout time';

    public function handle()
    {
        // Get session lifetime in minutes from config
        $sessionLifetime = config('session.lifetime', 120);
        
        // Calculate the cutoff time
        $cutoffTime = Carbon::now()->subMinutes($sessionLifetime);
        
        // Find sessions that are expired (no logout time and last activity before cutoff)
        $expiredSessions = UserSession::whereNull('logout_at')
            ->where(function($query) use ($cutoffTime) {
                $query->where('last_activity_at', '<', $cutoffTime)
                      ->orWhere(function($q) use ($cutoffTime) {
                          $q->whereNull('last_activity_at')
                            ->where('login_at', '<', $cutoffTime);
                      });
            })
            ->get();

        $count = $expiredSessions->count();
        
        foreach ($expiredSessions as $session) {
            $session->logout_at = $session->last_activity_at ?? $session->login_at;
            $session->save();
        }

        $this->info("Cleaned {$count} expired sessions.");
    }
} 