<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class EnsureXsrfToken
{
    /**
     * Handle an incoming request.
     * Ensures session is started and has a CSRF token available.
     * The CSRF token is automatically shared via Inertia props in HandleInertiaRequests.
     */
    public function handle(Request $request, Closure $next)
    {
        if (! $request->hasSession()) {
            $request->setLaravelSession(
                app('session')->driver()
            );
        }

        if (! $request->session()->isStarted()) {
            $request->session()->start();
        }

        if (! $request->session()->token()) {
            $request->session()->regenerateToken();
        }

        return $next($request);
    }
}
