<?php

declare(strict_types=1);

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

namespace App\Services\Plugin;

use App\Support\PluginRelease\OfficialPluginReleaseSigner;

/**
 * 官方插件发布包 signature.sig 校验（复用宿主签名配置）。
 */
final class HostPluginReleasePackageSignatureValidator
{
    public function isPlaceholder(string $signatureContents): bool
    {
        return trim($signatureContents) === trim(OfficialPluginReleaseSigner::PLACEHOLDER);
    }

    public function signatureRequired(): bool
    {
        return (bool) config('dberp.plugin.signature_required', false);
    }

    public function signatureVerificationEnabled(): bool
    {
        return (bool) config('dberp.plugin.signature_verification_enabled', true);
    }

    public function verifyArchiveSignature(string $archivePath, string $signatureContents): bool
    {
        if ($this->isPlaceholder($signatureContents)) {
            return false;
        }

        if (! $this->signatureVerificationEnabled()) {
            return true;
        }

        $publicKey = $this->resolvePublicKey();

        if ($publicKey === null) {
            return true;
        }

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

        if ($payload === '') {
            return false;
        }

        $verified = openssl_verify(
            $payload,
            $this->decodeSignature($signatureContents),
            $publicKey,
            $this->resolveAlgorithm(),
        );

        return $verified === 1;
    }

    private 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 resolvePublicKey(): mixed
    {
        $configured = config('dberp.plugin.signature_public_key');

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

        return openssl_pkey_get_public(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,
        };
    }

    private function decodeSignature(string $signature): string
    {
        $trimmed = trim($signature);

        if (str_contains($trimmed, '-----BEGIN')) {
            return $trimmed;
        }

        $decoded = base64_decode($trimmed, true);

        return $decoded !== false ? $decoded : $trimmed;
    }
}
