<?php

namespace App\Http\Middleware;

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

final class RememberNavigationTrail
{
    private const SESSION_KEY = 'erp_nav_recent';

    private const MAX = 6;

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

        $user = $request->user();
        if ($user === null || ! $request->isMethod('GET') || $request->expectsJson()) {
            return $response;
        }

        $route = $request->route();
        $name = $route?->getName();
        if ($name === null || str_starts_with($name, 'livewire.')) {
            return $response;
        }

        if (in_array($name, ['login', 'logout', 'register', 'password.request', 'password.reset', 'verification.notice'], true)) {
            return $response;
        }

        $url = $request->fullUrl();

        $stack = $request->session()->get(self::SESSION_KEY, []);
        if (! is_array($stack)) {
            $stack = [];
        }

        $stack = array_values(array_filter($stack, static fn ($row): bool => is_array($row) && (($row['url'] ?? '') !== $url)));
        array_unshift($stack, ['url' => $url, 'route' => $name]);
        $stack = array_slice($stack, 0, self::MAX);
        $request->session()->put(self::SESSION_KEY, $stack);

        return $response;
    }
}
