<?php

declare(strict_types=1);

namespace App\Http\Middleware;

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

class UseSystemSessionCookie
{
    /**
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $originalCookieName = (string) config('session.cookie');

        config(['session.cookie' => $this->systemCookieName()]);

        try {
            return $next($request);
        } finally {
            config(['session.cookie' => $originalCookieName]);
        }
    }

    private function systemCookieName(): string
    {
        return Str::slug((string) config('app.name', 'laravel')).'-system-session';
    }
}
