/**
 * Utility functions for safe log output.
 * Prevents sensitive data (passwords, tokens, secrets) from appearing in logs.
 */

const SENSITIVE_KEYS = new Set([
	'password',
	'password_hash',
	'new_password',
	'old_password',
	'confirm_password',
	'access_token',
	'refresh_token',
	'token',
	'secret',
	'api_key',
	'apikey',
	'authorization',
	'credit_card',
	'card_number',
	'cvv',
	'otp',
	'pin',
	'private_key',
	'client_secret',
	'zalo_code',
]);

const MASK = '***REDACTED***';

/**
 * Deeply traverse an object and replace values whose keys match the sensitive list.
 * Returns a new object (original is not mutated).
 * Handles nested objects and arrays up to 10 levels deep to prevent DoS on circular structures.
 */
export function maskSensitiveFields(input: unknown, depth = 0): unknown {
	if (depth > 10) return input;
	if (input === null || input === undefined) return input;
	if (typeof input !== 'object') return input;

	if (Array.isArray(input)) {
		return input.map((item) => maskSensitiveFields(item, depth + 1));
	}

	const result: Record<string, unknown> = {};
	for (const [key, value] of Object.entries(input as Record<string, unknown>)) {
		if (SENSITIVE_KEYS.has(key.toLowerCase())) {
			result[key] = MASK;
		} else {
			result[key] = maskSensitiveFields(value, depth + 1);
		}
	}
	return result;
}
