<?php

declare(strict_types=1);

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

namespace App\Support\PluginRelease;

use RuntimeException;

/**
 * 官方插件发布包签名：有私钥时生成真实签名，否则写入占位文件。
 */
class OfficialPluginReleaseSigner
{
    public const PLACEHOLDER = "UNSIGNED_PLACEHOLDER\n";

    /**
     * @return array{contents: string, signed: bool, strategy: string}
     */
    public function createSignatureContents(string $archivePath): array
    {
        $privateKey = $this->resolvePrivateKey();

        if ($privateKey === null) {
            return [
                'contents' => self::PLACEHOLDER,
                'signed' => false,
                'strategy' => 'placeholder',
            ];
        }

        $payload = $this->buildSignedPayload($archivePath);

        if ($payload === '') {
            throw new RuntimeException("Unable to read archive for signing: {$archivePath}");
        }

        $signature = '';

        if (! openssl_sign($payload, $signature, $privateKey, $this->resolveAlgorithm())) {
            throw new RuntimeException('Unable to sign plugin release archive.');
        }

        return [
            'contents' => base64_encode($signature).PHP_EOL,
            'signed' => true,
            'strategy' => 'openssl',
        ];
    }

    /**
     * @return array{path: string, signed: bool, strategy: string}
     */
    public function signOrPlaceholder(string $archivePath, string $outputDirectory): array
    {
        $signaturePath = $outputDirectory.DIRECTORY_SEPARATOR.'signature.sig';
        $signature = $this->createSignatureContents($archivePath);

        if (file_put_contents($signaturePath, $signature['contents']) === false) {
            throw new RuntimeException("Unable to write signature file: {$signaturePath}");
        }

        return [
            'path' => $signaturePath,
            'signed' => $signature['signed'],
            'strategy' => $signature['strategy'],
        ];
    }

    public function buildSignedPayload(string $archivePath): string
    {
        $zip = new \ZipArchive;
        $opened = $zip->open($archivePath);

        if ($opened !== true) {
            return '';
        }

        $entries = [];

        for ($index = 0; $index < $zip->numFiles; $index++) {
            $name = $zip->getNameIndex($index);

            if (! is_string($name) || $name === '' || str_ends_with($name, '/')) {
                continue;
            }

            if ($name === 'signature.sig') {
                continue;
            }

            $content = $zip->getFromIndex($index);

            if ($content === false) {
                $zip->close();

                return '';
            }

            $entries[$name] = $content;
        }

        $zip->close();
        ksort($entries, SORT_STRING);

        $payload = '';

        foreach ($entries as $name => $content) {
            $payload .= $name."\0".$content;
        }

        return $payload;
    }

    private function resolvePrivateKey(): mixed
    {
        $configured = config('dberp.plugin.signature_private_key');

        if (! is_string($configured) || trim($configured) === '') {
            return null;
        }

        return openssl_pkey_get_private(trim($configured)) ?: null;
    }

    private function resolveAlgorithm(): int
    {
        $configured = strtolower(trim((string) config('dberp.plugin.signature_algorithm', 'sha256')));

        return match ($configured) {
            'sha384' => OPENSSL_ALGO_SHA384,
            'sha512' => OPENSSL_ALGO_SHA512,
            default => OPENSSL_ALGO_SHA256,
        };
    }
}
