<?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\CorePlugin;
use App\Models\User;
use App\Services\DberpPermissionService;
use DBCore\Plugin\Enums\PluginStatus;
use Illuminate\Contracts\Auth\Authenticatable;
use Throwable;

/**
 * 解析已启用插件 manifest 中的 feature_entries，供插件中心展示业务入口链接。
 */
final class HostPluginFeatureEntryResolver
{
    public function __construct(
        private readonly DberpPluginDiscoveryManager $discoveryManager,
        private readonly HostPluginManifestFileReader $manifestFileReader,
        private readonly DberpPermissionService $permissionService,
    ) {}

    /**
     * @return list<array{label: string, url: string}>
     */
    public function entriesFor(string $identifier, ?Authenticatable $user): array
    {
        $normalized = trim($identifier);

        if ($normalized === '' || ! $this->isPluginEnabled($normalized)) {
            return [];
        }

        $manifest = $this->manifestFileReader->enriched($normalized);

        if (! is_array($manifest)) {
            return [];
        }

        $rawEntries = $manifest['feature_entries'] ?? [];

        if (! is_array($rawEntries)) {
            return [];
        }

        $entries = [];

        foreach ($rawEntries as $entry) {
            if (! is_array($entry)) {
                continue;
            }

            $label = trim((string) ($entry['label'] ?? ''));

            if ($label === '') {
                continue;
            }

            $permission = trim((string) ($entry['permission'] ?? ''));

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

            $url = $this->resolveEntryUrl($entry);

            if ($url === null) {
                continue;
            }

            $entries[] = [
                'label' => $label,
                'url' => $url,
            ];
        }

        return $entries;
    }

    /**
     * @param  array<string, mixed>  $entry
     */
    private function resolveEntryUrl(array $entry): ?string
    {
        $routeName = trim((string) ($entry['route'] ?? ''));

        if ($routeName !== '') {
            try {
                app('router')->getRoutes()->refreshNameLookups();

                $url = route($routeName);

                return is_string($url) && $url !== '' ? $url : null;
            } catch (Throwable) {
                return null;
            }
        }

        $path = trim((string) ($entry['url'] ?? ''));

        if ($path === '') {
            return null;
        }

        return str_starts_with($path, '/') ? url($path) : $path;
    }

    private function isPluginEnabled(string $identifier): bool
    {
        $record = CorePlugin::query()->where('identifier', $identifier)->first();

        return $record !== null && (string) $record->status === PluginStatus::Enabled->value;
    }

    private function userHasPermission(?Authenticatable $user, string $permission): bool
    {
        if (! $user instanceof User) {
            return false;
        }

        return $this->permissionService->allows($user, $permission);
    }
}
