<?php

declare(strict_types=1);

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

namespace App\Support;

/**
 * 插件中心「设置」侧滑：插件摘要块 + 通用兜底信息。
 */
final class HostPluginCenterSettingsPanelFormatter
{
    public function __construct(
        private readonly HostPluginSettingsPanelRegistry $registry,
    ) {}

    /**
     * @param  array<string, mixed>  $row
     */
    public function shouldOfferPanel(array $row): bool
    {
        return (bool) ($row['show_settings_action'] ?? false);
    }

    /**
     * @param  array<string, mixed>  $row
     */
    public function fullSettingsUrl(array $row): ?string
    {
        $url = $row['settings_url'] ?? null;

        return filled($url) ? (string) $url : null;
    }

    /**
     * @param  array<string, mixed>  $row
     * @return list<array{
     *     kind: string,
     *     label?: string,
     *     value?: string,
     *     tone?: string,
     *     url?: string,
     *     links?: list<array{label: string, url: string}>
     * }>
     */
    public function blocksForPanel(array $row): array
    {
        $identifier = (string) ($row['identifier'] ?? '');
        $provider = $this->registry->resolve($identifier);

        if ($provider !== null) {
            return $provider->summaryBlocks($row);
        }

        return $this->genericBlocks($row);
    }

    /**
     * @param  array<string, mixed>  $row
     * @return list<array{
     *     kind: string,
     *     label?: string,
     *     value?: string,
     *     tone?: string,
     *     url?: string,
     *     links?: list<array{label: string, url: string}>
     * }>
     */
    private function genericBlocks(array $row): array
    {
        $blocks = [
            [
                'kind' => 'text',
                'value' => (string) __('dberp.plugin_center.settings.panel_generic_intro'),
            ],
        ];

        if (filled($row['version'] ?? null)) {
            $blocks[] = [
                'kind' => 'field',
                'label' => (string) __('dberp.plugin_center.installed.columns.version'),
                'value' => (string) $row['version'],
            ];
        }

        if (filled($row['status_label'] ?? null)) {
            $blocks[] = [
                'kind' => 'badge',
                'label' => (string) __('dberp.plugin_center.installed.columns.status'),
                'value' => (string) $row['status_label'],
                'tone' => (string) ($row['status_color'] ?? 'gray'),
            ];
        }

        return $blocks;
    }
}
