<?php

declare(strict_types=1);

namespace App\Services\SupportCenter;

use App\Models\HostSystemAuthorization;
use App\Support\HostSystemAuthorizationCenterDisplay;
use Illuminate\Support\Carbon;

/**
 * 官方系统更新权益门禁（非 RBAC 替代；UI/操作需与本地权限并用）。
 *
 * 免费 DBErp 主程序（Phase 1 全量包）在线更新：检查 / 下载 / 执行仅需系统接入与 Support Center 连通。
 * 商业授权、服务状态与 can_execute_system_update 等权益保留给商业增强包、插件及商业专属更新通道（见 commercial* 方法）。
 */
final class HostSystemUpdateEntitlementGate
{
    public function __construct(
        private readonly SupportCenterConnectivityGuard $connectivityGuard,
        private readonly SupportCenterUserFacingErrors $userFacingErrors,
        private readonly HostSystemAuthorizationCenterDisplay $authorizationCenterDisplay,
    ) {}

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

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

    public function canDownloadPackage(): bool
    {
        return $this->canExecuteUpdate();
    }

    public function downloadReason(): string
    {
        return $this->executeReason();
    }

    /**
     * 商业增强包 / 插件 / 商业专属更新通道（后续接入；当前主程序一键更新不调用）。
     */
    public function canExecuteCommercialUpdate(): bool
    {
        return $this->commercialExecuteReasonCode() === null;
    }

    public function canDownloadCommercialPackage(): bool
    {
        return $this->canExecuteCommercialUpdate();
    }

    public function commercialExecuteReason(): string
    {
        $code = $this->commercialExecuteReasonCode();

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

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

    public function checkReason(): string
    {
        $code = $this->freeMainProgramReasonCode();

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

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

    public function executeReason(): string
    {
        $code = $this->freeMainProgramReasonCode();

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

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

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

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

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

        return null;
    }

    private function commercialExecuteReasonCode(): ?string
    {
        $freeMainCode = $this->freeMainProgramReasonCode();

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

        $authorization = HostSystemAuthorization::singleton();

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

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

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

        if (! $this->entitlementEnabled($authorization, 'can_execute_system_update')) {
            return 'execute_entitlement_denied';
        }

        return null;
    }

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

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

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

    private function isServiceExpired(?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.system_update.entitlement.'.$code;

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

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