<?php

declare(strict_types=1);

namespace App\Services\SupportCenter;

/**
 * 清理 Support Center 快照中的敏感字段，避免持久化或展示密钥。
 */
final class SupportCenterSnapshotSanitizer
{
    /**
     * @var list<string>
     */
    private const SENSITIVE_KEY_FRAGMENTS = [
        'host_token',
        'host_key',
        'access_code',
        'authorization',
        'download_token',
        'token',
        'secret',
        'password',
        'license_key',
    ];

    /**
     * @param  array<string, mixed>  $data
     * @return array<string, mixed>
     */
    public static function sanitize(array $data): array
    {
        $sanitized = [];

        foreach ($data as $key => $value) {
            if (! is_string($key) || self::isSensitiveKey($key)) {
                continue;
            }

            if (is_array($value)) {
                /** @var array<string, mixed> $value */
                $sanitized[$key] = self::sanitize($value);

                continue;
            }

            if (is_string($value) && self::containsSensitiveFragment($value)) {
                continue;
            }

            $sanitized[$key] = $value;
        }

        return $sanitized;
    }

    private static function isSensitiveKey(string $key): bool
    {
        $normalized = strtolower($key);

        foreach (self::SENSITIVE_KEY_FRAGMENTS as $fragment) {
            if (str_contains($normalized, $fragment)) {
                return true;
            }
        }

        return false;
    }

    private static function containsSensitiveFragment(string $value): bool
    {
        $normalized = strtolower($value);

        foreach (self::SENSITIVE_KEY_FRAGMENTS as $fragment) {
            if (str_contains($normalized, $fragment)) {
                return true;
            }
        }

        return false;
    }
}
