<?php

declare(strict_types=1);

function logMessage(string $level, string $message, array $context = []): void
{
    $line = json_encode([
        'time' => date('c'),
        'level' => $level,
        'message' => $message,
        'context' => redactSensitiveData($context),
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

    file_put_contents((string) config('LOG_FILE'), $line . PHP_EOL, FILE_APPEND | LOCK_EX);
}

function redactSensitiveData($value)
{
    if (is_array($value)) {
        $redacted = [];
        foreach ($value as $key => $item) {
            $normalizedKey = strtolower((string) $key);
            if (
                str_contains($normalizedKey, 'token')
                || str_contains($normalizedKey, 'secret')
                || in_array($normalizedKey, ['auth', 'authorization', 'auth_id', 'refresh_id', 'app_sid'], true)
            ) {
                $redacted[$key] = '[redacted]';
                continue;
            }

            $redacted[$key] = redactSensitiveData($item);
        }

        return $redacted;
    }

    if (is_string($value)) {
        return preg_replace(
            '/((access_token|refresh_token|application_token|AUTH_ID|REFRESH_ID|APP_SID)=)[^&\s]+/i',
            '$1[redacted]',
            $value
        );
    }

    return $value;
}
