<?php

namespace App\Listeners;

use Illuminate\Auth\Events\Logout;
use Illuminate\Support\Facades\Log;
use App\Models\UserSession;

class LogUserLogout
{
    /**
     * Handle the event.
     */
    public function handle(Logout $event): void
    {
        if (!$event->user) {
            Log::warning('Logout event fired without user payload', [
                'session_id' => session()->getId(),
                'ip' => request()->ip(),
                'user_agent' => request()->userAgent(),
            ]);
            return;
        }

        // Log the logout event
        Log::info('User logged out', [
            'user_id' => $event->user->id,
            'session_id' => session()->getId(),
            'ip' => request()->ip(),
            'user_agent' => request()->userAgent()
        ]);

        // Update user_sessions table for auditing
        $userSession = UserSession::where('user_id', $event->user->id)
            ->where('session_id', session()->getId())
            ->where('status', 'active')
            ->first();

        if ($userSession) {
            $userSession->update([
                'logged_out_at' => now(),
                'status' => 'logged_out',
            ]);
        }

        // Update user offline status for chat
        $event->user?->update(['status' => 'offline']);
    }
}
