<?php

namespace App\Support;

class CronLogSanitizer
{
    /**
     * @param  array<string|int, mixed>  $values
     * @return array<string|int, mixed>
     */
    public function sanitizeInput(array $values): array
    {
        foreach ($values as $key => $value) {
            if (preg_match('/token|secret|password|authorization|api[_-]?key|cookie/i', (string) $key)) {
                $values[$key] = '[REDACTED]';
            } elseif (is_array($value)) {
                $values[$key] = $this->sanitizeInput($value);
            } elseif (is_string($value)) {
                $values[$key] = $this->sanitizeText($value);
            }
        }

        return $values;
    }

    public function sanitizeText(string $text): string
    {
        $text = preg_replace('/\bBearer\s+[A-Za-z0-9._~+\/-]+/i', 'Bearer [REDACTED]', $text) ?? $text;

        return preg_replace(
            '/\b(access[_-]?token|x-cron-token|token|password|secret|authorization|api[_-]?key)(["\']?\s*[:=]\s*["\']?)[^"\'\s,;&}\]]+/i',
            '$1$2[REDACTED]',
            $text,
        ) ?? $text;
    }
}
