<?php

declare(strict_types=1);

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

namespace App\Services\SupportCenter;

use App\Models\HostSystemUpdatePackage;
use Illuminate\Support\Facades\Log;
use Throwable;

/**
 * 更新包签名校验（可选）；整包 checksum 校验仍为强制项。
 */
final class HostSystemUpdatePackageSignatureVerifier
{
    public function __construct(
        private readonly SupportCenterAuditLogger $auditLogger,
    ) {}

    public function verifyIfConfigured(HostSystemUpdatePackage $package): HostSystemUpdatePackage
    {
        $signature = $this->nullableString($package->signature);

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

            return $package;
        }

        if (! $this->signatureVerificationEnabled()) {
            if ($this->signatureRequired()) {
                return $this->markSignatureFailed(
                    $package,
                    (string) __('dberp.system_update.package.signature_verify_failed'),
                    'signature_verification_disabled',
                );
            }

            $this->auditLogger->logSystemUpdatePackageSignatureSkipped($package);

            return $package;
        }

        $publicKey = $this->resolvePublicKey();

        if ($publicKey === null) {
            Log::warning('support_center.system_update.signature_verification_not_configured', [
                'package_id' => $package->package_id,
            ]);

            return $this->markSignatureFailed(
                $package,
                (string) __('dberp.system_update.package.signature_verify_failed'),
                'signature_public_key_missing',
            );
        }

        $path = $package->local_path;

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

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

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

        $publicKeyHandle = @openssl_pkey_get_public($publicKey);

        if ($publicKeyHandle === false) {
            return $this->markSignatureFailed(
                $package,
                (string) __('dberp.system_update.package.signature_verify_failed'),
                'signature_public_key_invalid',
            );
        }

        try {
            $verified = @openssl_verify(
                $payload,
                $this->decodeSignature($signature),
                $publicKeyHandle,
                $this->resolveAlgorithm(),
            );
        } catch (Throwable) {
            return $this->markSignatureFailed(
                $package,
                (string) __('dberp.system_update.package.signature_verify_failed'),
                'signature_verify_failed',
            );
        }

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

        $package->fill([
            'download_message' => null,
            'download_error_code' => null,
        ]);
        $package->save();

        $this->auditLogger->logSystemUpdatePackageSignatureVerified($package->fresh() ?? $package);

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

    private function signatureVerificationEnabled(): bool
    {
        return filter_var(
            config('dberp.system_update.verify_package_signature', false),
            FILTER_VALIDATE_BOOLEAN,
        );
    }

    private function signatureRequired(): bool
    {
        return filter_var(
            config('dberp.system_update.require_package_signature', false),
            FILTER_VALIDATE_BOOLEAN,
        );
    }

    private function resolvePublicKey(): ?string
    {
        $configured = config('dberp.system_update.signature_public_key');

        if (is_string($configured) && trim($configured) !== '') {
            $trimmed = trim($configured);

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

            if (is_file($trimmed)) {
                $contents = @file_get_contents($trimmed);

                return is_string($contents) && trim($contents) !== '' ? $contents : null;
            }
        }

        $path = config('dberp.system_update.signature_public_key_path');

        if (is_string($path) && is_file($path)) {
            $contents = @file_get_contents($path);

            return is_string($contents) && trim($contents) !== '' ? $contents : null;
        }

        return null;
    }

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

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

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

        if (str_contains($normalized, ':')) {
            [, $value] = array_pad(explode(':', $normalized, 2), 2, '');
            $normalized = trim((string) $value);
        }

        $decoded = base64_decode($normalized, true);

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

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

        $this->auditLogger->logSystemUpdatePackageSignatureVerificationFailed($package->fresh() ?? $package);

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

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

        $trimmed = trim($value);

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