/**
 * Utilities for redacting sensitive values before they are returned in API responses.
 * 
 * This module ensures API keys, tokens, and other credentials are never exposed
 * in their raw form via REST endpoints.
 */

/** Pattern matching env variable names that typically hold secrets. */
const SENSITIVE_KEY_PATTERN = /(?:api[_-]?key|secret|token|password|credential|auth[_-]?token|private[_-]?key)/i;

/**
 * Determine whether an environment variable name suggests a sensitive value.
 */
export function isSensitiveKey(key: string): boolean {
  return SENSITIVE_KEY_PATTERN.test(key);
}

/**
 * Mask a sensitive value for safe display.
 *
 * - Empty / whitespace-only strings → `""` (nothing to redact)
 * - Values ≤ 4 characters → `"****"` (too short to safely reveal any suffix)
 * - Longer values → `"****<last4>"` so the user can identify which key is configured
 */
export function redactValue(value: string): string {
  const trimmed = value.trim();
  if (!trimmed) return "";
  if (trimmed.length <= 4) return "****";
  return `****${trimmed.slice(-4)}`;
}

/**
 * Return a copy of `variables` with sensitive values masked.
 * Non-sensitive keys are left untouched.
 */
export function redactEnvVariables(
  variables: Record<string, string>,
): Record<string, string> {
  const redacted: Record<string, string> = {};
  for (const [key, value] of Object.entries(variables)) {
    redacted[key] = isSensitiveKey(key) ? redactValue(value) : value;
  }
  return redacted;
}
