<?php

namespace App\Listeners;

use App\Models\User;
use Illuminate\Auth\Events\Logout;
use Illuminate\Support\Facades\Cache;

class HandleUserLogout
{
    public function handle(Logout $event): void
    {
        if (!$event->user instanceof User) {
            return;
        }

        $user = $event->user;
        $now = now();

        $user->forceFill([
            'last_logout_at'   => $now,
            'last_activity_at' => $now->copy()->subMinutes(5),
        ])->save();

        // Remove online cache
        Cache::forget($user->onlineCacheKey());
    }
}