<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use App\Models\User;
use App\Services\DberpAdminMenuShortcutService;
use Closure;
use Filament\Facades\Filament;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * 在 Filament 认证通过后注册侧栏「常用功能」固定项：panel() 配置阶段尚无登录用户，不能在此处构建固定菜单。
 * 仅当存在至少一条当前用户可访问的固定记录时才注册，避免「常用功能」分组空白占位。
 */
final class RegisterDberpPinnedShortcutNavigationItems
{
    public function __construct(
        private readonly DberpAdminMenuShortcutService $menuShortcutService,
    ) {}

    public function handle(Request $request, Closure $next): Response
    {
        $panel = Filament::getCurrentPanel();
        $user = $request->user();

        if ($panel !== null && $panel->getId() === 'admin' && $user instanceof User) {
            $items = $this->menuShortcutService->pinnedShortcutNavigationItems($user);
            if ($items !== []) {
                $panel->navigationItems($items);
            }
        }

        return $next($request);
    }
}
