<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureXsrfCookie
{
    public function handle(Request $request, Closure $next): Response
    {
        /** @var Response $response */
        $response = $next($request);

        if ($request->isMethod('GET') && ! $request->cookies->has('XSRF-TOKEN')) {
            $response->headers->setCookie(
                cookie(
                    name: 'XSRF-TOKEN',
                    value: csrf_token(),
                    minutes: 120,
                    path: '/',
                    domain: null,
                    secure: $request->isSecure(),
                    httpOnly: false,
                    raw: false,
                    sameSite: 'lax'
                )
            );
        }

        return $response;
    }
}
