<?php

declare(strict_types=1);

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