<?php

declare(strict_types=1);

namespace App\Services\SupportCenter;

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

/**
 * 更新包签名校验（可选）；整包 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()) {
            $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,
            ]);
            $this->auditLogger->logSystemUpdatePackageSignatureSkipped($package);

            return $package;
        }

        $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',
            );
        }

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

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