<?php

declare(strict_types=1);

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

namespace App\Filament\Support;

use App\Services\Plugin\HostPluginNavigationCatalog;

/**
 * 从已启用官方插件 manifest navigation 生成「可固定到常用功能」的候选项。
 */
final class DberpPluginNavigationShortcutCatalog
{
    public function __construct(
        private readonly HostPluginNavigationCatalog $navigationCatalog,
    ) {}

    /**
     * @return list<DberpShortcutItem>
     */
    public function discover(): array
    {
        $items = [];

        foreach ($this->navigationCatalog->businessNavigationEntries() as $entry) {
            $routeName = $entry['route_name'];
            $identifier = $entry['identifier'];

            $items[] = new DberpShortcutItem(
                key: 'plugin.'.$identifier.'.'.$routeName,
                labelLangKey: 'dberp.shortcuts.plugin_nav.label',
                descriptionLangKey: null,
                resourceClass: null,
                pageClass: null,
                permissionCodesAny: null,
                group: 'plugin_nav',
                sort: $entry['sort'],
                placements: [DberpShortcutRegistry::PLACEMENT_SIDEBAR_PINNABLE],
                openResourceCreate: false,
                usesFilamentNavigationLabel: false,
                navigationUiGroup: $this->navigationCatalog->resolveNavigationGroupLabel($entry['group_key']),
                routeName: $routeName,
                directLabel: $entry['label'],
                permissionCode: $entry['permission'],
            );
        }

        usort($items, static function (DberpShortcutItem $a, DberpShortcutItem $b): int {
            $ra = DberpAdminSidebarNavigationOrder::rankForResolvedLabel($a->sectionLabel());
            $rb = DberpAdminSidebarNavigationOrder::rankForResolvedLabel($b->sectionLabel());
            if ($ra !== $rb) {
                return $ra <=> $rb;
            }
            if ($a->sidebarNavigationSort() !== $b->sidebarNavigationSort()) {
                return $a->sidebarNavigationSort() <=> $b->sidebarNavigationSort();
            }

            return strcmp($a->localizedLabel(), $b->localizedLabel());
        });

        return $items;
    }
}
