import { ValidationLogEntry, XSSValidationLogEntry } from './types';

/**
 * Central security logging service for file validation events
 * Records all validation attempts for audit and investigation
 */
export class SecurityLogger {
  private logs: ValidationLogEntry[] = [];
  private xssLogs: XSSValidationLogEntry[] = [];

  /**
   * Log a validation event
   * @param entry - Validation log entry with all required metadata
   */
  async logValidationEvent(entry: ValidationLogEntry): Promise<void> {
    try {
      // Ensure timestamp is set
      if (!entry.timestamp) {
        entry.timestamp = new Date();
      }

      // Store log entry
      this.logs.push(entry);

      // In production, this would write to a secure logging service
      // For now, we log to console in development
      if (process.env.NODE_ENV === 'development') {
        console.log('[SECURITY LOG]', {
          timestamp: entry.timestamp.toISOString(),
          module: entry.module,
          endpoint: entry.endpoint,
          result: entry.validationResult,
          declaredMime: entry.declaredMime,
          detectedMime: entry.detectedMime,
          error: entry.errorDetails,
        });
      }

      // TODO: In production, integrate with your logging service
      // Examples:
      // - Send to CloudWatch, DataDog, Splunk, etc.
      // - Write to database audit table
      // - Send to centralized logging system
    } catch (error) {
      console.error('Failed to log validation event:', error);
      // Don't throw - logging failures shouldn't break uploads
    }
  }

  /**
   * Log an XSS validation event
   * @param entry - XSS validation log entry
   */
  async logXSSValidationEvent(entry: XSSValidationLogEntry): Promise<void> {
    try {
      // Ensure timestamp is set
      if (!entry.timestamp) {
        entry.timestamp = new Date();
      }

      // Store log entry
      this.xssLogs.push(entry);

      // Log to console in development
      if (process.env.NODE_ENV === 'development') {
        console.log('[XSS VALIDATION LOG]', {
          timestamp: entry.timestamp.toISOString(),
          module: entry.module,
          uploadContext: entry.uploadContext,
          result: entry.validationResult,
          fileName: entry.sanitizedFileName, // Use sanitized name for logging
          declaredMime: entry.declaredMimeType,
          detectedMime: entry.detectedMimeType,
          failureReason: entry.failureReason,
        });
      }

      // TODO: In production, integrate with your logging service
      // Ensure sensitive file content is NOT logged
    } catch (error) {
      console.error('Failed to log XSS validation event:', error);
      // Don't throw - logging failures shouldn't break uploads
    }
  }

  /**
   * Query validation logs for investigation
   * @param filters - Filter criteria for logs
   * @returns Matching log entries
   */
  async queryValidationLogs(filters: {
    module?: string;
    validationResult?: string;
    startDate?: Date;
    endDate?: Date;
    userId?: string;
  }): Promise<ValidationLogEntry[]> {
    return this.logs.filter((log) => {
      if (filters.module && log.module !== filters.module) return false;
      if (
        filters.validationResult &&
        log.validationResult !== filters.validationResult
      )
        return false;
      if (filters.startDate && log.timestamp < filters.startDate) return false;
      if (filters.endDate && log.timestamp > filters.endDate) return false;
      if (filters.userId && log.userId !== filters.userId) return false;
      return true;
    });
  }

  /**
   * Query XSS validation logs for investigation
   * @param filters - Filter criteria for logs
   * @returns Matching XSS validation log entries
   */
  async queryXSSValidationLogs(filters: {
    module?: string;
    uploadContext?: string;
    validationResult?: string;
    startDate?: Date;
    endDate?: Date;
    userId?: string;
  }): Promise<XSSValidationLogEntry[]> {
    return this.xssLogs.filter((log) => {
      if (filters.module && log.module !== filters.module) return false;
      if (filters.uploadContext && log.uploadContext !== filters.uploadContext)
        return false;
      if (
        filters.validationResult &&
        log.validationResult !== filters.validationResult
      )
        return false;
      if (filters.startDate && log.timestamp < filters.startDate) return false;
      if (filters.endDate && log.timestamp > filters.endDate) return false;
      if (filters.userId && log.userId !== filters.userId) return false;
      return true;
    });
  }

  /**
   * Get all logs (for testing/debugging)
   */
  getAllLogs(): ValidationLogEntry[] {
    return [...this.logs];
  }

  /**
   * Get all XSS validation logs (for testing/debugging)
   */
  getAllXSSLogs(): XSSValidationLogEntry[] {
    return [...this.xssLogs];
  }

  /**
   * Clear logs (for testing)
   */
  clearLogs(): void {
    this.logs = [];
    this.xssLogs = [];
  }
}

// Export singleton instance
export const securityLogger = new SecurityLogger();
