<?php
declare(strict_types=1);
namespace App\Platform\Soc\Event;

final class EventSanitizer
{
    private const BLOCKED_KEYS = [
        'password', 'mot_de_passe', 'passwd', 'token', 'authorization',
        'cookie', 'csrf', 'session', 'credential', 'private_key', 'api_key',
    ];

    /** @param array<string,mixed> $metadata @return array<string,mixed> */
    public static function sanitize(array $metadata): array
    {
        $safe = [];
        foreach ($metadata as $key => $value) {
            $name = mb_substr((string) $key, 0, 120);
            $lower = strtolower($name);
            $blocked = false;
            foreach (self::BLOCKED_KEYS as $needle) {
                if (str_contains($lower, $needle)) { $blocked = true; break; }
            }
            if ($blocked) {
                $safe[$name] = '[REDACTED]';
                continue;
            }
            $safe[$name] = self::value($value, 0);
        }
        return $safe;
    }

    private static function value(mixed $value, int $depth): mixed
    {
        if ($depth >= 3) return '[MAX_DEPTH]';
        if ($value === null || is_bool($value) || is_int($value) || is_float($value)) return $value;
        if (is_string($value)) return mb_substr($value, 0, 1000);
        if (!is_array($value)) return '[UNSUPPORTED_VALUE]';
        $result = [];
        $count = 0;
        foreach ($value as $key => $item) {
            if (++$count > 50) { $result['_truncated'] = true; break; }
            $result[mb_substr((string) $key, 0, 120)] = self::value($item, $depth + 1);
        }
        return $result;
    }
}
