<?php

declare(strict_types=1);

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

namespace App\Support\PluginRelease;

/**
 * 构建 DBErp 官方插件发布 manifest.json（schema: dberp-plugin-release-v1）。
 */
class OfficialPluginReleaseManifestBuilder
{
    public const SCHEMA = 'dberp-plugin-release-v1';

    public const PRODUCT_CODE = 'dberp';

    /**
     * @param  array<string, mixed>  $pluginManifest
     * @return array<string, mixed>
     */
    public function build(
        array $pluginManifest,
        string $version,
        string $archiveFilename,
        string $archiveSha256,
        int $archiveSizeBytes,
    ): array {
        $pluginCode = trim((string) ($pluginManifest['alias'] ?? ''));
        $pluginName = trim((string) ($pluginManifest['name'] ?? ''));

        $manifest = [
            'schema' => self::SCHEMA,
            'product_code' => self::PRODUCT_CODE,
            'plugin_code' => $pluginCode,
            'plugin_name' => $pluginName,
            'version' => $version,
            'archive' => [
                'filename' => $archiveFilename,
                'sha256' => strtolower($archiveSha256),
                'size_bytes' => $archiveSizeBytes,
            ],
            'built_at' => gmdate('c'),
        ];

        $compatibility = $this->resolveCompatibility($pluginManifest);

        if ($compatibility !== []) {
            $manifest['compatibility'] = $compatibility;
        }

        return $manifest;
    }

    public function toJson(array $manifest): string
    {
        return (string) json_encode(
            $manifest,
            JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
        ).PHP_EOL;
    }

    /**
     * @param  array<string, mixed>  $pluginManifest
     * @return array<string, string>
     */
    private function resolveCompatibility(array $pluginManifest): array
    {
        $compatibility = [];

        if (! isset($pluginManifest['requires']) || ! is_array($pluginManifest['requires'])) {
            return $compatibility;
        }

        /** @var array<string, mixed> $requires */
        $requires = $pluginManifest['requires'];

        foreach (['dberp', 'php'] as $key) {
            if (! isset($requires[$key])) {
                continue;
            }

            $value = trim((string) $requires[$key]);

            if ($value !== '') {
                $compatibility[$key] = $value;
            }
        }

        return $compatibility;
    }
}
