/**
 * Timestamp Security Utilities
 * Provides functions to sanitize and mask timestamp data to prevent information disclosure
 */

/**
 * Sanitizes timestamp data from API responses
 * Removes or masks Unix timestamps and other timing information
 */
export function sanitizeTimestamps(data: any): any {
  if (!data) return data;
  
  // If it's an array, sanitize each item
  if (Array.isArray(data)) {
    return data.map(item => sanitizeTimestamps(item));
  }
  
  // If it's an object, sanitize each property
  if (typeof data === 'object') {
    const sanitized: any = {};
    
    for (const [key, value] of Object.entries(data)) {
      // Skip timestamp-related fields that could expose server information
      if (isTimestampField(key)) {
        // Convert to user-friendly date format instead of exposing raw timestamps
        if (typeof value === 'number' && value > 1000000000) {
          // Convert Unix timestamp to readable date (removes precision)
          sanitized[key] = new Date(value * 1000).toLocaleDateString();
        } else if (typeof value === 'string' && isISODateString(value)) {
          // Convert ISO date to readable format
          sanitized[key] = new Date(value).toLocaleDateString();
        } else {
          // Keep non-timestamp values as is
          sanitized[key] = value;
        }
      } else {
        // Recursively sanitize nested objects
        sanitized[key] = sanitizeTimestamps(value);
      }
    }
    
    return sanitized;
  }
  
  return data;
}

/**
 * Checks if a field name indicates it contains timestamp data
 */
function isTimestampField(fieldName: string): boolean {
  const timestampFields = [
    'timestamp',
    'created_at',
    'updated_at',
    'modified_at',
    'published_at',
    'date_created',
    'date_modified',
    'last_modified',
    'created_time',
    'updated_time',
    'unix_time',
    'epoch',
    'time'
  ];
  
  const lowerFieldName = fieldName.toLowerCase();
  return timestampFields.some(field => 
    lowerFieldName.includes(field) || 
    lowerFieldName.endsWith('_time') || 
    lowerFieldName.endsWith('_date')
  );
}

/**
 * Checks if a string is an ISO date string
 */
function isISODateString(value: string): boolean {
  const isoDateRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z?$/;
  return isoDateRegex.test(value);
}

/**
 * Masks sensitive timing information in error messages
 */
export function sanitizeErrorMessage(error: any): string {
  if (!error) return 'An error occurred';
  
  let message = typeof error === 'string' ? error : error.message || 'An error occurred';
  
  // Remove timestamp patterns from error messages
  message = message.replace(/\d{10,13}/g, '[TIMESTAMP_REMOVED]');
  message = message.replace(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z?/g, '[DATETIME_REMOVED]');
  message = message.replace(/at \d{2}:\d{2}:\d{2}/g, 'at [TIME_REMOVED]');
  
  return message;
}

/**
 * Creates a safe date string for display without exposing precise timing
 */
export function createSafeDisplayDate(date?: string | number | Date): string {
  if (!date) return '';
  
  try {
    const dateObj = new Date(date);
    // Return only date without time to avoid timing disclosure
    return dateObj.toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  } catch {
    return '';
  }
}