<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

namespace App\Services\Plugin;

use App\Models\User;
use App\Services\DberpPermissionService;
use Filament\Navigation\NavigationItem;

use function Filament\Support\original_request;

/**
 * 为已启用且声明了 navigation 的官方插件注册可选 Filament 侧栏入口。
 */
final class HostPluginNavigationRegistrar
{
    public function __construct(
        private readonly HostPluginNavigationCatalog $navigationCatalog,
        private readonly DberpPermissionService $permissionService,
    ) {}

    /**
     * @return list<NavigationItem>
     */
    public function navigationItemsFor(User $user): array
    {
        $items = [];

        foreach ($this->navigationCatalog->businessNavigationEntries() as $entry) {
            $permission = trim($entry['permission']);

            if ($permission !== '' && ! $this->permissionService->allows($user, $permission)) {
                continue;
            }

            $item = $this->buildNavigationItem($entry);

            if ($item !== null) {
                $items[] = $item;
            }
        }

        return $items;
    }

    /**
     * @param  array{identifier: string, manifest: array<string, mixed>, label: string, route_name: string, permission: string, group_key: string, sort: int, active_routes: list<string>|null, icon: string|null}  $entry
     */
    private function buildNavigationItem(array $entry): ?NavigationItem
    {
        $label = $entry['label'];
        $routeName = $entry['route_name'];
        $manifest = $entry['manifest'];
        $identifier = $entry['identifier'];

        $item = NavigationItem::make($label)
            ->url(route($routeName))
            ->isActiveWhen(fn (): bool => $this->navigationRouteIsActive(
                $routeName,
                $identifier,
                $manifest,
                $entry['active_routes'],
            ))
            ->sort($entry['sort']);

        $groupKey = trim($entry['group_key']);

        if ($groupKey !== '') {
            $item->group($this->navigationCatalog->resolveNavigationGroupLabel($groupKey));
        }

        $icon = $entry['icon'] ?? null;

        if (is_string($icon) && trim($icon) !== '') {
            $item->icon(trim($icon));
        }

        return $item;
    }

    /**
     * 插件业务导航高亮：主路由 + 同插件业务子路由；设置页（config_route）不高亮侧栏业务入口。
     *
     * @param  array<string, mixed>  $manifest
     * @param  list<string>|null  $activeRoutePatterns
     */
    private function navigationRouteIsActive(
        string $primaryRouteName,
        string $identifier,
        array $manifest,
        ?array $activeRoutePatterns = null,
    ): bool {
        $request = original_request();
        $routePrefix = trim((string) ($manifest['alias'] ?? $identifier));
        $settingsRoute = trim((string) ($manifest['config_route'] ?? ''));

        if ($settingsRoute === '' && $routePrefix !== '') {
            $settingsRoute = $routePrefix.'.settings';
        }

        if ($settingsRoute !== '' && $request->routeIs($settingsRoute)) {
            return $primaryRouteName === $settingsRoute && $request->routeIs($settingsRoute);
        }

        if (is_array($activeRoutePatterns) && $activeRoutePatterns !== []) {
            return $request->routeIs($activeRoutePatterns);
        }

        if ($settingsRoute !== '' && $primaryRouteName === $settingsRoute) {
            return $request->routeIs($settingsRoute);
        }

        if ($request->routeIs($primaryRouteName)) {
            return true;
        }

        if ($routePrefix === '') {
            return false;
        }

        return $request->routeIs($routePrefix.'.*');
    }
}
