<?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 App\Support\PluginIntegration\HostOfficialPluginViewPermissions;
use DBCore\Plugin\Enums\PluginStatus;
use Illuminate\Contracts\Auth\Authenticatable;

/**
 * 为官方插件生成插件中心「使用指引」展示数据。
 */
final class HostPluginOfficialUsageGuidanceResolver
{
    private const BARCODE_LABEL = 'dberp-barcode-label';

    private const ADVANCED_IMPORT_EXPORT = 'dberp-advanced-import-export';

    private const INVOICE_ASSISTANT = 'dberp-invoice-assistant';

    private const NOTIFICATION_CHANNEL = 'dberp-notification-channel';

    private const LIGHT_APPROVAL = 'dberp-light-approval';

    public function __construct(
        private readonly DberpPermissionService $permissionService,
        private readonly HostPluginManifestFileReader $manifestFileReader,
    ) {}

    /**
     * @param  list<array{label: string, url: string}>  $featureEntries
     * @return array{
     *     description: string,
     *     main_entry_label: string,
     *     main_entry_url: ?string,
     *     import_entry_label?: string,
     *     export_entry_label?: string,
     *     host_locations: list<string>,
     *     settings_purpose: string,
     *     permission_status_label: string,
     *     permission_status_tone: string,
     *     permission_hint: ?string,
     *     disabled_hint: ?string,
     *     quick_links: list<array{label: string, url: string}>
     * }|null
     */
    public function resolve(
        string $identifier,
        ?Authenticatable $user,
        string $status,
        array $featureEntries,
    ): ?array {
        $guidanceKey = match (trim($identifier)) {
            self::BARCODE_LABEL => 'dberp_barcode_label',
            self::ADVANCED_IMPORT_EXPORT => 'dberp_advanced_import_export',
            self::INVOICE_ASSISTANT => 'dberp_invoice_assistant',
            self::NOTIFICATION_CHANNEL => 'dberp_notification_channel',
            self::LIGHT_APPROVAL => 'dberp_light_approval',
            default => null,
        };

        if ($guidanceKey === null) {
            return null;
        }

        $manifest = $this->manifestFileReader->enriched(trim($identifier));
        $description = $this->resolveDescription($manifest, $guidanceKey);
        $isEnabled = $status === PluginStatus::Enabled->value;
        $viewPermission = HostOfficialPluginViewPermissions::forGuidanceKey($guidanceKey);
        $hasViewPermission = $user instanceof User
            && $viewPermission !== ''
            && $this->permissionService->allows($user, $viewPermission);

        $disabledHint = $isEnabled
            ? null
            : (string) __('dberp.plugin_center.usage_guidance.disabled_hint');
        $permissionHint = ($isEnabled && ! $hasViewPermission)
            ? (string) __('dberp.plugin_center.usage_guidance.permission_denied')
            : null;

        $permissionStatus = match (true) {
            ! $isEnabled => [
                'label' => (string) __('dberp.plugin_center.usage_guidance.permission_status.disabled'),
                'tone' => 'gray',
            ],
            ! $hasViewPermission => [
                'label' => (string) __('dberp.plugin_center.usage_guidance.permission_status.no_access'),
                'tone' => 'warning',
            ],
            default => [
                'label' => (string) __('dberp.plugin_center.usage_guidance.permission_status.available'),
                'tone' => 'success',
            ],
        };

        /** @var list<string> $hostLocations */
        $hostLocations = trans("dberp.plugin_center.usage_guidance.{$guidanceKey}.host_locations");
        if (! is_array($hostLocations)) {
            $hostLocations = [];
        }

        $quickLinks = ($isEnabled && $hasViewPermission) ? $featureEntries : [];

        $mainEntryUrl = $this->resolveMainEntryUrl($quickLinks, $guidanceKey);

        $guidance = [
            'description' => $description,
            'main_entry_label' => (string) __("dberp.plugin_center.usage_guidance.{$guidanceKey}.main_entry"),
            'main_entry_url' => $mainEntryUrl,
            'host_locations' => array_values(array_map(strval(...), $hostLocations)),
            'settings_purpose' => (string) __("dberp.plugin_center.usage_guidance.{$guidanceKey}.settings_purpose"),
            'permission_status_label' => $permissionStatus['label'],
            'permission_status_tone' => $permissionStatus['tone'],
            'permission_hint' => $permissionHint,
            'disabled_hint' => $disabledHint,
            'quick_links' => $quickLinks,
        ];

        if ($guidanceKey === 'dberp_advanced_import_export') {
            $guidance['export_entry_label'] = (string) __("dberp.plugin_center.usage_guidance.{$guidanceKey}.export_entry");
        }

        return $guidance;
    }

    /**
     * @param  array<string, mixed>|null  $manifest
     */
    private function resolveDescription(?array $manifest, string $guidanceKey): string
    {
        $manifestDescription = trim((string) ($manifest['description'] ?? ''));

        if ($manifestDescription !== '') {
            return $manifestDescription;
        }

        return (string) __("dberp.plugin_center.usage_guidance.{$guidanceKey}.description");
    }

    /**
     * @param  list<array{label: string, url: string}>  $quickLinks
     */
    private function resolveMainEntryUrl(array $quickLinks, string $guidanceKey): ?string
    {
        if ($quickLinks === []) {
            return null;
        }

        $preferredLabel = match ($guidanceKey) {
            'dberp_barcode_label' => '进入标签打印',
            'dberp_advanced_import_export' => '进入主数据Excel导出',
            'dberp_invoice_assistant' => '进入发票管理',
            'dberp_notification_channel' => '进入消息通知',
            'dberp_light_approval' => '进入审批中心',
            default => null,
        };

        if ($preferredLabel !== null) {
            foreach ($quickLinks as $entry) {
                if (($entry['label'] ?? '') === $preferredLabel) {
                    return $entry['url'] ?? null;
                }
            }
        }

        return $quickLinks[0]['url'] ?? null;
    }
}
