<?php

declare(strict_types=1);

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

namespace App\Services\SupportCenter;

/**
 * Support Center 错误码与用户可见中文文案映射。
 */
final class SupportCenterUserFacingErrors
{
    public const SUPPORT_CENTER_DISABLED = 'support_center_disabled';

    public const STUB_MODE_ENABLED = 'stub_mode_enabled';

    public const BASE_URL_NOT_CONFIGURED = 'base_url_not_configured';

    public const BASE_URL_MISSING = 'base_url_missing';

    public const HOST_TOKEN_NOT_CONFIGURED = 'host_token_not_configured';

    public const RELEASE_CREDENTIAL_MISSING = 'release_credential_missing';

    public const ENV_FALLBACK_MISSING = 'env_fallback_missing';

    public const UNAUTHORIZED_CREDENTIAL = 'unauthorized_credential';

    public const PRODUCT_LINE_INVALID = 'product_line_invalid';

    public const SITE_BINDING_IDENTITY_MISMATCH = 'site_binding_identity_mismatch';

    public const VALIDATION_TASK_EXPIRED = 'validation_task_expired';

    public const SITE_BINDING_ALREADY_BOUND = 'site_binding_already_bound';

    public const SITE_BINDING_DOMAIN_MISMATCH = 'site_binding_domain_mismatch';

    public const SITE_BINDING_CALLBACK_FAILED = 'site_binding_callback_failed';

    public const SITE_BINDING_PENDING_MANUAL_REVIEW = 'site_binding_pending_manual_review';

    public const NETWORK_TIMEOUT = 'network_timeout';

    public const REMOTE_SERVICE_UNAVAILABLE = 'remote_service_unavailable';

    public const INVALID_RESPONSE_FORMAT = 'invalid_response_format';

    public const UNKNOWN_REMOTE_ERROR = 'unknown_remote_error';

    public const REMOTE_PACKAGE_FETCH_DENIED = 'remote_package_fetch_denied';

    public const REMOTE_DOWNLOAD_TOKEN_DENIED = 'remote_download_token_denied';

    public const REMOTE_UPDATE_NOT_ENTITLED = 'remote_update_not_entitled';

    public const REMOTE_PLUGIN_CLAIM_DENIED = 'remote_plugin_claim_denied';

    public const REMOTE_PLUGIN_NOT_AVAILABLE = 'remote_plugin_not_available';

    /**
     * @var array<string, string>
     */
    private const MESSAGES = [
        self::SUPPORT_CENTER_DISABLED => '官方支撑中心未启用，暂无法建立远程连接。',
        self::STUB_MODE_ENABLED => '当前处于支撑中心 Stub 模式，未发起真实远程请求。',
        self::BASE_URL_NOT_CONFIGURED => '官方支撑中心服务地址未就绪，请联系服务商或技术支持协助处理。',
        self::BASE_URL_MISSING => '官方支撑中心服务地址未就绪，请联系服务商或技术支持协助处理。',
        self::HOST_TOKEN_NOT_CONFIGURED => '官方接入凭证未就绪，请联系服务商或技术支持协助处理。',
        self::RELEASE_CREDENTIAL_MISSING => '当前安装包未包含官方接入凭证，请联系服务商获取官方发布包或由技术支持协助处理。',
        self::ENV_FALLBACK_MISSING => '当前环境未完成官方支撑中心接入配置，请联系系统管理员在受控环境中补全后再试。',
        self::UNAUTHORIZED_CREDENTIAL => '官方接入凭证无效或已失效，请重新绑定或更新凭证。',
        self::PRODUCT_LINE_INVALID => '当前产品线未开通或不可用，请联系官方支撑确认授权范围。',
        self::SITE_BINDING_IDENTITY_MISMATCH => '站点绑定身份与当前安装实例不一致，请核对域名与实例标识。',
        self::VALIDATION_TASK_EXPIRED => '站点校验任务已过期，请重新发起绑定流程。',
        self::SITE_BINDING_ALREADY_BOUND => '该站点已完成绑定，无需重复提交接入码。',
        self::SITE_BINDING_DOMAIN_MISMATCH => '当前访问域名与绑定申请不一致，请核对域名后重试。',
        self::SITE_BINDING_CALLBACK_FAILED => '站点校验回传失败，请检查固定校验文件或网络后重试，或联系官方支持。',
        self::SITE_BINDING_PENDING_MANUAL_REVIEW => '绑定申请已进入人工复核，请等待官方处理结果。',
        self::NETWORK_TIMEOUT => '连接官方支撑中心超时，请稍后重试或检查网络。',
        self::REMOTE_SERVICE_UNAVAILABLE => '官方支撑中心暂时不可用，请稍后重试。',
        self::INVALID_RESPONSE_FORMAT => '官方支撑中心返回了无法识别的响应格式。',
        self::UNKNOWN_REMOTE_ERROR => '官方支撑中心返回未知错误，请稍后重试或联系技术支持。',
    ];

    /**
     * @var array<string, string>
     */
    private const REMOTE_CODE_ALIASES = [
        'unauthorized' => self::UNAUTHORIZED_CREDENTIAL,
        'invalid_credentials' => self::UNAUTHORIZED_CREDENTIAL,
        'host_unauthorized' => self::UNAUTHORIZED_CREDENTIAL,
        'invalid_token' => self::UNAUTHORIZED_CREDENTIAL,
        'product_invalid' => self::PRODUCT_LINE_INVALID,
        'product_not_activated' => self::PRODUCT_LINE_INVALID,
        'product_line_invalid' => self::PRODUCT_LINE_INVALID,
        'site_identity_mismatch' => self::SITE_BINDING_IDENTITY_MISMATCH,
        'binding_identity_mismatch' => self::SITE_BINDING_IDENTITY_MISMATCH,
        'validation_expired' => self::VALIDATION_TASK_EXPIRED,
        'task_expired' => self::VALIDATION_TASK_EXPIRED,
        'site_binding_task_expired' => self::VALIDATION_TASK_EXPIRED,
        'site_binding_task_not_accessible' => self::SITE_BINDING_PENDING_MANUAL_REVIEW,
        'site_binding_identity_mismatch' => self::SITE_BINDING_IDENTITY_MISMATCH,
        'site_binding_already_bound_for_customer' => self::SITE_BINDING_ALREADY_BOUND,
        'site_binding_foreign_customer_bound' => self::SITE_BINDING_ALREADY_BOUND,
        'site_binding_presence_domain_mismatch' => self::SITE_BINDING_DOMAIN_MISMATCH,
        'site_binding_validation_failed' => self::SITE_BINDING_CALLBACK_FAILED,
        'site_binding_product_line_mismatch' => self::PRODUCT_LINE_INVALID,
        'site_binding_task_not_found' => self::UNKNOWN_REMOTE_ERROR,
        'site_binding_application_state_invalid' => self::UNKNOWN_REMOTE_ERROR,
        'auth_host_unauthorized' => self::UNAUTHORIZED_CREDENTIAL,
        'timeout' => self::NETWORK_TIMEOUT,
        'service_unavailable' => self::REMOTE_SERVICE_UNAVAILABLE,
        'invalid_response' => self::INVALID_RESPONSE_FORMAT,
        'entitlement_denied' => self::REMOTE_UPDATE_NOT_ENTITLED,
        'not_entitled' => self::REMOTE_UPDATE_NOT_ENTITLED,
        'update_not_entitled' => self::REMOTE_UPDATE_NOT_ENTITLED,
        'package_not_entitled' => self::REMOTE_UPDATE_NOT_ENTITLED,
        'download_token_denied' => self::REMOTE_DOWNLOAD_TOKEN_DENIED,
        'package_download_denied' => self::REMOTE_PACKAGE_FETCH_DENIED,
        'package_fetch_denied' => self::REMOTE_PACKAGE_FETCH_DENIED,
        'forbidden' => self::REMOTE_PACKAGE_FETCH_DENIED,
        'product_code_mismatch' => self::PRODUCT_LINE_INVALID,
        'plugin_product_code_mismatch' => self::PRODUCT_LINE_INVALID,
        'claim_denied' => self::REMOTE_PLUGIN_CLAIM_DENIED,
        'plugin_claim_denied' => self::REMOTE_PLUGIN_CLAIM_DENIED,
        'plugin_not_found' => self::REMOTE_PLUGIN_NOT_AVAILABLE,
        'plugin_unavailable' => self::REMOTE_PLUGIN_NOT_AVAILABLE,
    ];

    /**
     * @var array<string, string>
     */
    private const REMOTE_PLUGIN_LANG_KEYS = [
        self::PRODUCT_LINE_INVALID => 'product_line_invalid',
        self::REMOTE_PACKAGE_FETCH_DENIED => 'package_fetch_denied',
        self::REMOTE_DOWNLOAD_TOKEN_DENIED => 'download_token_denied',
        self::REMOTE_UPDATE_NOT_ENTITLED => 'update_not_entitled',
        self::REMOTE_PLUGIN_CLAIM_DENIED => 'claim_denied',
        self::REMOTE_PLUGIN_NOT_AVAILABLE => 'plugin_not_available',
        'product_code_mismatch' => 'product_code_mismatch',
    ];

    /**
     * @var array<string, string>
     */
    private const REMOTE_UPDATE_LANG_KEYS = [
        self::REMOTE_PACKAGE_FETCH_DENIED => 'package_fetch_denied',
        self::REMOTE_DOWNLOAD_TOKEN_DENIED => 'download_token_denied',
        self::REMOTE_UPDATE_NOT_ENTITLED => 'update_not_entitled',
    ];

    public function messageFor(?string $errorCode, ?string $remoteMessage = null): string
    {
        if ($errorCode !== null) {
            $pluginLangSuffix = self::REMOTE_PLUGIN_LANG_KEYS[$errorCode] ?? null;

            if ($pluginLangSuffix !== null) {
                $pluginTranslationKey = 'dberp.plugin_center.remote.'.$pluginLangSuffix;

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

            $remoteLangSuffix = self::REMOTE_UPDATE_LANG_KEYS[$errorCode] ?? $errorCode;
            $remoteTranslationKey = 'dberp.system_update.remote.'.$remoteLangSuffix;

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

        if ($errorCode !== null && isset(self::MESSAGES[$errorCode])) {
            return self::MESSAGES[$errorCode];
        }

        if ($remoteMessage !== null && trim($remoteMessage) !== '' && ! $this->containsSensitiveValue($remoteMessage)) {
            return trim($remoteMessage);
        }

        return self::MESSAGES[self::UNKNOWN_REMOTE_ERROR];
    }

    public function messageForSystemUpdate(?string $errorCode, ?string $remoteMessage = null): string
    {
        if ($errorCode !== null) {
            $remoteLangSuffix = self::REMOTE_UPDATE_LANG_KEYS[$errorCode] ?? null;

            if ($remoteLangSuffix !== null) {
                $translationKey = 'dberp.system_update.remote.'.$remoteLangSuffix;

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

        return $this->messageFor($errorCode, $remoteMessage);
    }

    public function resolveCode(?string $remoteCode): string
    {
        if ($remoteCode === null || trim($remoteCode) === '') {
            return self::UNKNOWN_REMOTE_ERROR;
        }

        $normalized = strtolower(trim($remoteCode));

        return self::REMOTE_CODE_ALIASES[$normalized] ?? $normalized;
    }

    public function containsSensitiveValue(string $value): bool
    {
        $lower = strtolower($value);

        foreach (['host_token', 'host_key', 'access_token', 'bearer ', 'secret'] as $needle) {
            if (str_contains($lower, $needle)) {
                return true;
            }
        }

        return false;
    }
}
