<?php

declare(strict_types=1);

namespace App\Services\SupportCenter;

/**
 * 自检输出脱敏：禁止 token、密钥与敏感路径泄露到命令行或诊断。
 */
final class SupportCenterCheckOutputSanitizer
{
    public function __construct(
        private readonly SupportCenterUserFacingErrors $userFacingErrors,
    ) {}

    public function sanitize(?string $value): ?string
    {
        if ($value === null) {
            return null;
        }

        $trimmed = trim($value);

        if ($trimmed === '') {
            return null;
        }

        if ($this->userFacingErrors->containsSensitiveValue($trimmed)) {
            return '[redacted]';
        }

        if ($this->looksLikeBearerToken($trimmed)) {
            return '[redacted]';
        }

        if ($this->looksLikeLongSecret($trimmed)) {
            return '[redacted]';
        }

        return $this->maskReleaseCredentialPath($trimmed);
    }

    public function sanitizeBaseUrlForDisplay(?string $baseUrl): ?string
    {
        if ($baseUrl === null || trim($baseUrl) === '') {
            return null;
        }

        $normalized = rtrim(trim($baseUrl), '/');
        $host = parse_url($normalized, PHP_URL_HOST);

        if (is_string($host) && $host !== '') {
            $scheme = parse_url($normalized, PHP_URL_SCHEME);

            return is_string($scheme) && $scheme !== ''
                ? $scheme.'://'.$host
                : $host;
        }

        return $normalized;
    }

    private function looksLikeBearerToken(string $value): bool
    {
        return preg_match('/^Bearer\s+\S+/i', $value) === 1;
    }

    private function looksLikeLongSecret(string $value): bool
    {
        if (strlen($value) < 24) {
            return false;
        }

        return preg_match('/^[A-Za-z0-9_\-]{24,}$/', $value) === 1
            && str_contains(strtolower($value), 'token') === false;
    }

    private function maskReleaseCredentialPath(string $value): string
    {
        if (! str_contains($value, 'support-center-open-host.json')) {
            return $value;
        }

        return '[release_credentials_file]';
    }
}
