<?php

declare(strict_types=1);

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

namespace App\Services\SupportCenter;

use App\Exceptions\SupportCenter\SupportCenterException;

/**
 * 判断是否允许发起真实 Support Center HTTP 请求。
 */
final class SupportCenterConnectivityGuard
{
    public function __construct(
        private readonly SupportCenterRuntimeConfig $runtimeConfig,
        private readonly SupportCenterCredentialResolver $credentialResolver,
    ) {}

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

    public function blockingReasonCode(): ?string
    {
        if (! $this->runtimeConfig->enabled()) {
            return SupportCenterUserFacingErrors::SUPPORT_CENTER_DISABLED;
        }

        if ($this->runtimeConfig->useStub()) {
            return SupportCenterUserFacingErrors::STUB_MODE_ENABLED;
        }

        $baseUrlReason = $this->credentialResolver->baseUrlBlockingReasonCode();

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

        $hostTokenReason = $this->credentialResolver->hostTokenBlockingReasonCode();

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

        return null;
    }

    public function assertRealCallsAllowed(?string $operation = null): void
    {
        $reason = $this->blockingReasonCode();

        if ($reason === null) {
            return;
        }

        throw SupportCenterException::connectivityBlocked($reason, $operation);
    }

    /**
     * @return array{
     *     has_host_token: bool,
     *     has_host_key: bool,
     *     has_base_url: bool,
     *     credential_source: ?string,
     * }
     */
    public function credentialPresence(): array
    {
        return $this->credentialResolver->credentialPresenceForLogs();
    }
}
