<?php

declare(strict_types=1);

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

namespace App\Services\SupportCenter;

use App\Enums\SupportCenter\SupportCenterCheckSeverity;
use App\Exceptions\SupportCenter\SupportCenterException;

/**
 * 可选远程连通性探测（仅应在 CLI 显式传入 --remote 时使用）。
 */
final class SupportCenterRemoteProbe
{
    public function __construct(
        private readonly SupportCenterConnectivityGuard $connectivityGuard,
        private readonly SupportCenterOpenApiTransport $transport,
        private readonly SupportCenterRequestContextBuilder $contextBuilder,
        private readonly SupportCenterCheckOutputSanitizer $outputSanitizer,
    ) {}

    public function probeRow(): SupportCenterCheckRow
    {
        $blocking = $this->connectivityGuard->blockingReasonCode();

        if ($blocking !== null) {
            return new SupportCenterCheckRow(
                id: 'remote_connectivity',
                severity: SupportCenterCheckSeverity::Error,
                label: '远程连通性探测未执行（本地配置未就绪）',
                reasonCode: $blocking,
            );
        }

        try {
            $this->transport->post(
                SupportCenterOpenHostEndpoints::SITE_PRESENCE,
                $this->contextBuilder->sitePresenceBody('local_readiness_probe'),
                'support_center_local_readiness_probe',
            );

            return new SupportCenterCheckRow(
                id: 'remote_connectivity',
                severity: SupportCenterCheckSeverity::Ok,
                label: '远程连通性探测成功',
            );
        } catch (SupportCenterException $exception) {
            return new SupportCenterCheckRow(
                id: 'remote_connectivity',
                severity: SupportCenterCheckSeverity::Warn,
                label: '远程连通性探测失败',
                reasonCode: SupportCenterSelfCheckReasonCodes::REMOTE_PROBE_FAILED,
                detail: $this->outputSanitizer->sanitize($exception->errorCode()),
            );
        }
    }
}
