<?php

declare(strict_types=1);

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