<?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\HostSystemAuthorization;
use App\Services\SupportCenter\SupportCenterConnectivityGuard;
use App\Services\SupportCenter\SupportCenterUserFacingErrors;
use App\Support\HostSystemAuthorizationCenterDisplay;
use Illuminate\Support\Carbon;

/**
 * 官方插件权益门禁：与免费主程序更新权益分离，需商业授权与 can_install_plugin / can_update_plugin。
 */
final class HostPluginEntitlementGate
{
    public function __construct(
        private readonly SupportCenterConnectivityGuard $connectivityGuard,
        private readonly SupportCenterUserFacingErrors $userFacingErrors,
        private readonly HostSystemAuthorizationCenterDisplay $authorizationCenterDisplay,
    ) {}

    public function canInstallPlugin(): bool
    {
        return $this->installReasonCode() === null;
    }

    public function canUpdatePlugin(): bool
    {
        return $this->updateReasonCode() === null;
    }

    public function prerequisitesSatisfied(): bool
    {
        return $this->canInstallPlugin() && $this->canUpdatePlugin();
    }

    public function commercialBaselineMet(): bool
    {
        return $this->baseCommercialReasonCode() === null;
    }

    public function installReason(): string
    {
        $code = $this->installReasonCode();

        if ($code === null) {
            return (string) __('dberp.plugin_center.entitlement.allowed_install');
        }

        return $this->messageForReasonCode($code);
    }

    public function updateReason(): string
    {
        $code = $this->updateReasonCode();

        if ($code === null) {
            return (string) __('dberp.plugin_center.entitlement.allowed_update');
        }

        return $this->messageForReasonCode($code);
    }

    public function hasSiteBinding(): bool
    {
        return $this->authorizationCenterDisplay->hasSiteBinding();
    }

    public function isServiceExpired(): bool
    {
        return $this->isServiceExpiredAt(HostSystemAuthorization::singleton()->expires_at);
    }

    public function connectivityBlocksRemoteOperations(): bool
    {
        return $this->connectivityGuard->blockingReasonCode() !== null;
    }

    /**
     * 免费主程序更新权益不得用于插件安装或更新。
     */
    public function freeMainUpdateAllowsPluginInstall(): bool
    {
        return $this->freeMainUpdateEntitlementEnabled();
    }

    public function freeMainUpdateAllowsPluginUpdate(): bool
    {
        return $this->freeMainUpdateEntitlementEnabled();
    }

    private function freeMainUpdateEntitlementEnabled(): bool
    {
        $authorization = HostSystemAuthorization::singleton();
        $entitlements = $authorization->entitlements;

        if (! is_array($entitlements)) {
            return false;
        }

        return filter_var($entitlements['can_download_free_main_update'] ?? false, FILTER_VALIDATE_BOOLEAN);
    }

    private function installReasonCode(): ?string
    {
        $baseCode = $this->baseCommercialReasonCode();

        if ($baseCode !== null) {
            return $baseCode;
        }

        if (! $this->entitlementEnabled('can_install_plugin')) {
            return 'install_entitlement_denied';
        }

        return null;
    }

    private function updateReasonCode(): ?string
    {
        $baseCode = $this->baseCommercialReasonCode();

        if ($baseCode !== null) {
            return $baseCode;
        }

        if (! $this->entitlementEnabled('can_update_plugin')) {
            return 'update_entitlement_denied';
        }

        return null;
    }

    private function baseCommercialReasonCode(): ?string
    {
        $connectivityCode = $this->connectivityGuard->blockingReasonCode();

        if ($connectivityCode !== null) {
            return $connectivityCode;
        }

        if (! $this->authorizationCenterDisplay->hasSiteBinding()) {
            return 'site_access_not_completed';
        }

        $authorization = HostSystemAuthorization::singleton();

        if (! $authorization->authorized) {
            return 'authorization_not_granted';
        }

        if ($this->isServiceExpiredAt($authorization->expires_at)) {
            return 'service_expired';
        }

        if (! $this->isServiceActive($authorization->service_status)) {
            return 'service_not_active';
        }

        return null;
    }

    private function entitlementEnabled(string $key): bool
    {
        $authorization = HostSystemAuthorization::singleton();
        $entitlements = $authorization->entitlements;

        if (! is_array($entitlements) || ! array_key_exists($key, $entitlements)) {
            return false;
        }

        return filter_var($entitlements[$key], FILTER_VALIDATE_BOOLEAN);
    }

    private function isServiceExpiredAt(?Carbon $expiresAt): bool
    {
        if ($expiresAt === null) {
            return false;
        }

        return $expiresAt->isPast();
    }

    private function isServiceActive(?string $serviceStatus): bool
    {
        if ($serviceStatus === null || trim($serviceStatus) === '') {
            return true;
        }

        return in_array(strtolower(trim($serviceStatus)), ['active', 'normal', 'enabled'], true);
    }

    private function messageForReasonCode(string $code): string
    {
        $translationKey = 'dberp.plugin_center.entitlement.'.$code;

        if (__($translationKey) !== $translationKey) {
            return (string) __($translationKey);
        }

        return $this->userFacingErrors->messageFor($code);
    }
}
