<?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\HostPluginPackage;
use Illuminate\Support\Facades\Log;

/**
 * 官方插件安装包签名校验（可选；校验和仍为强制项）。
 */
final class HostPluginPackageSignatureVerifier
{
    public function verifyIfConfigured(HostPluginPackage $package): HostPluginPackage
    {
        $signature = $this->nullableString($package->signature);

        if ($signature === null) {
            if ($this->signatureRequired()) {
                return $this->markSignatureFailed(
                    $package,
                    (string) __('dberp.plugin_center.package.signature_missing'),
                    'signature_missing',
                );
            }

            return $package;
        }

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

        $publicKey = $this->resolvePublicKey();

        if ($publicKey === null) {
            Log::warning('dberp.plugin_center.signature_verification_not_configured', [
                'plugin_code' => $package->plugin_code,
            ]);

            return $package;
        }

        $path = $package->local_path;

        if (! is_string($path) || $path === '' || ! is_file($path)) {
            return $this->markSignatureFailed(
                $package,
                (string) __('dberp.plugin_center.package.verification_file_missing'),
                'signature_file_missing',
            );
        }

        $payload = (string) @file_get_contents($path);

        if ($payload === '') {
            return $this->markSignatureFailed(
                $package,
                (string) __('dberp.plugin_center.package.signature_verify_failed'),
                'signature_verify_failed',
            );
        }

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

        if ($verified !== 1) {
            return $this->markSignatureFailed(
                $package,
                (string) __('dberp.plugin_center.package.signature_mismatch'),
                'signature_mismatch',
            );
        }

        return $package;
    }

    private function markSignatureFailed(
        HostPluginPackage $package,
        string $message,
        string $errorCode,
    ): HostPluginPackage {
        $package->fill([
            'verified' => false,
            'verified_at' => null,
            'download_status' => HostPluginPackage::STATUS_VERIFICATION_FAILED,
            'download_message' => $message,
            'download_error_code' => $errorCode,
        ]);
        $package->save();

        return $package->fresh() ?? $package;
    }

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

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

    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;
    }

    private function nullableString(mixed $value): ?string
    {
        if (! is_string($value)) {
            return null;
        }

        $trimmed = trim($value);

        return $trimmed === '' ? null : $trimmed;
    }
}
