const SECRET_TOKENS = [
  'access_token',
  'refresh_token',
  'client_secret',
  'authorization',
  'code_verifier',
  'id_token',
];

export function redactSecrets<T>(value: T): T {
  if (value === null || value === undefined) return value;
  if (Array.isArray(value)) {
    return value.map((v) => redactSecrets(v)) as unknown as T;
  }
  if (typeof value === 'object') {
    const out: Record<string, unknown> = {};
    for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
      const lower = k.toLowerCase();
      if (SECRET_TOKENS.some((s) => lower.includes(s))) {
        out[k] = '***';
      } else if (lower === 'code') {
        // Stand-alone "code" key is always an authorization code in OAuth payloads; redact.
        out[k] = '***';
      } else {
        out[k] = redactSecrets(v);
      }
    }
    return out as T;
  }
  return value;
}
