<?php

namespace App\Console\Commands;

use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;

class ClearExpiredSessions extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sessions:clear-expired';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Clear expired user sessions based on SESSION_LIFETIME configuration';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Starting to clear expired sessions...');
        
        // Get session lifetime from ParameterGlobal (fallback to config)
        $sessionLifetime = \App\Models\ParameterGlobal::getSessionLifetime();
        
        // Calculate expiration time
        $expirationTime = Carbon::now()->subMinutes($sessionLifetime);
        
        $this->info("Session lifetime: {$sessionLifetime} minutes");
        $this->info("Clearing sessions older than: {$expirationTime->format('Y-m-d H:i:s')}");
        
        // Find users with active sessions that have expired
        $expiredUsers = User::whereNotNull('current_session_id')
            ->where('last_login_at', '<', $expirationTime)
            ->get();
        
        $clearedCount = 0;
        
        foreach ($expiredUsers as $user) {
            $lastLoginDiff = Carbon::parse($user->last_login_at)->diffForHumans();
            
            $user->clearSession();
            $clearedCount++;
            
            $this->line("✓ Cleared session for user: {$user->username} (Last login: {$lastLoginDiff})");
            
            Log::info("Auto-cleared expired session", [
                'user_id' => $user->id,
                'username' => $user->username,
                'last_login_at' => $user->last_login_at,
                'session_lifetime' => $sessionLifetime
            ]);
        }
        
        if ($clearedCount > 0) {
            $this->info("✓ Successfully cleared {$clearedCount} expired session(s)");
        } else {
            $this->info("✓ No expired sessions found");
        }
        
        return Command::SUCCESS;
    }
}
