<?php

namespace App\Listeners;

use App\Models\UserSession;
use Illuminate\Auth\Events\Login;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Request;

class LogUserLogin implements ShouldQueue
{
    /**
     * Create the event listener.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle(Login $event): void
    {
        // Log session
        UserSession::create([
            'user_id' => $event->user->id,
            'session_id' => session()->getId(),
            'ip_address' => Request::ip(),
            'user_agent' => Request::userAgent(),
            'logged_in_at' => now(),
            'status' => 'active',
        ]);

        // Update user online status for chat
        $event->user->update(['status' => 'online']);
        
        // Update chat participants last_seen
        $event->user->chatParticipants()->update(['last_seen' => now()]);
    }
}
