<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Support\Facades\Auth;
use App\Models\UserSession;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route('login');
        }
    }

    protected function authenticate($request, array $guards)
    {
        parent::authenticate($request, $guards);
        // Update only last_activity_at for the latest session
        if (Auth::check()) {
            UserSession::where('user_id', Auth::id())
                ->whereNull('logout_at')
                ->orderByDesc('login_at')
                ->first()
                ?->update(['last_activity_at' => now()->setTimezone('UTC')]);
        }
    }
}
