import * as winston from 'winston';
import { utilities as nestWinstonUtilities } from 'nest-winston';
import * as path from 'path';

/**
 * Winston logging configuration for NestJS applications
 *
 * This configuration sets up a robust logging system using Winston with:
 * - Multiple transport destinations (files and console)
 * - Different log levels for different purposes
 * - Structured logging format
 * - Integration with NestJS's logging utilities
 *
 * Log files are stored in a 'logs' directory in the application root.
 *
 * @example
 * // In main.ts to bootstrap the application with Winston
 * app.useLogger(app.get(WINSTON_MODULE_PROVIDER));
 *
 * // In any service/controller
 * constructor(private readonly logger: Logger) {}
 * this.logger.log('Info message');
 * this.logger.error('Error message', error.stack);
 */
const logDir = path.join(process.cwd(), 'logs');

export const winstonConfig = {
  /**
   * Array of log transports - defines where logs are sent
   *
   * Each transport can have different configurations, levels, and formats
   * allowing for flexible log routing and storage strategies
   */
  transports: [
    /**
     * File transport for INFO level and above logs
     *
     * Stores general application logs to 'logs/app.log'
     * Useful for debugging, auditing, and monitoring normal application flow
     *
     * @remarks Logs 'info', 'warn', and 'error' levels
     * @example Contains: Startup messages, request logs, business logic events
     */
    new winston.transports.File({
      /**
       * Absolute path to the general application log file
       *
       * @example On Unix: '/home/user/app/logs/app.log'
       * @example On Windows: 'C:\Projects\app\logs\app.log'
       */
      filename: path.join(logDir, 'app.log'),

      /**
       * Minimum log level to capture
       *
       * Levels in Winston (from highest to lowest priority):
       * error: 0, warn: 1, info: 2, verbose: 3, debug: 4, silly: 5
       *
       * @remarks 'info' level includes: info, warn, and error
       */
      level: 'info',
    }),

    /**
     * File transport for ERROR level logs only
     *
     * Stores error logs separately to 'logs/error.log'
     * Useful for error monitoring, alerting, and debugging production issues
     *
     * @remarks Only logs 'error' level (highest severity)
     * @example Contains: Unhandled exceptions, API errors, system failures
     */
    new winston.transports.File({
      /**
       * Absolute path to the error-specific log file
       *
       * Keeping errors separate makes it easier to:
       * - Set up error monitoring alerts
       * - Analyze error patterns
       * - Archive critical issues
       */
      filename: path.join(logDir, 'error.log'),

      /**
       * Only capture error-level logs
       *
       * This creates a clean error-only log file for focused debugging
       */
      level: 'error',
    }),

    /**
     * Console transport for development and debugging
     *
     * Outputs logs to the console with a NestJS-friendly format
     * Includes colors, timestamps, and clean formatting for readability
     *
     * @remarks Typically disabled in production or configured differently
     * @example Output: [TIMESTAMP] [CONTEXT] LOG_LEVEL: Message
     */
    new winston.transports.Console({
      /**
       * Format configuration for console output
       *
       * Combines multiple format transformers to create readable console output
       */
      format: winston.format.combine(
        /**
         * Adds timestamps to each log entry
         *
         * @default 'YYYY-MM-DD HH:mm:ss' format
         * @example [2024-01-15 14:30:45]
         */
        winston.format.timestamp(),

        /**
         * NestJS-specific formatter for console output
         *
         * Provides:
         * - Color-coded log levels
         * - Context information (service/controller name)
         * - Clean, readable formatting
         * - NestJS application metadata
         */
        nestWinstonUtilities.format.nestLike(),
      ),
    }),
  ],
};

/**
 * Advanced Configuration and Usage Notes:
 *
 * 1. **Log Rotation and Management**:
 *    Consider adding log rotation for production:
 *
 *    ```typescript
 *    import * as winston from 'winston';
 *    import 'winston-daily-rotate-file';
 *
 *    new winston.transports.DailyRotateFile({
 *      filename: path.join(logDir, 'application-%DATE%.log'),
 *      datePattern: 'YYYY-MM-DD',
 *      maxSize: '20m',
 *      maxFiles: '14d',
 *      level: 'info'
 *    })
 *    ```
 *
 * 2. **Environment-Based Configuration**:
 *
 *    ```typescript
 *    const isProduction = process.env.NODE_ENV === 'production';
 *
 *    const transports = [
 *      // Always log to files
 *      new winston.transports.File({ /* ... *\/ }),
 *
 *      // Only log to console in development
 *      ...(isProduction ? [] : [
 *        new winston.transports.Console({ /* ... *\/ })
 *      ])
 *    ];
 *    ```
 *
 * 3. **Custom Log Formatting**:
 *
 *    ```typescript
 *    const customFormat = winston.format.combine(
 *      winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
 *      winston.format.errors({ stack: true }), // Include error stack traces
 *      winston.format.splat(), // String interpolation
 *      winston.format.json(), // JSON format for machine parsing
 *      winston.format.metadata({ fillExcept: ['message', 'level', 'timestamp'] })
 *    );
 *    ```
 *
 * 4. **Log Levels and Usage Guidelines**:
 *    - error: System failures, unrecoverable errors, crashes
 *    - warn: Unexpected situations, deprecated API usage, slow operations
 *    - info: Business logic events, successful operations, system state changes
 *    - verbose: Detailed debugging information, request/response bodies
 *    - debug: Technical debugging, variable dumps, internal state
 *
 * 5. **Directory Creation and Permissions**:
 *
 *    ```typescript
 *    // Ensure log directory exists
 *    import * as fs from 'fs';
 *    if (!fs.existsSync(logDir)) {
 *      fs.mkdirSync(logDir, { recursive: true });
 *    }
 *    ```
 *
 * 6. **Integration with Monitoring Tools**:
 *    - Export logs to ELK Stack (Elasticsearch, Logstash, Kibana)
 *    - Send to CloudWatch (AWS) or Stackdriver (GCP)
 *    - Integrate with application monitoring (New Relic, DataDog)
 *    - Set up log-based alerts for critical errors
 *
 * 7. **Performance Considerations**:
 *    - Use async logging for high-volume applications
 *    - Consider log sampling for verbose levels in production
 *    - Compress rotated log files to save disk space
 *    - Monitor log file sizes and implement retention policies
 *
 * 8. **Testing Configuration**:
 *
 *    ```typescript
 *    // Test that logging works correctly
 *    const logger = winston.createLogger(winstonConfig);
 *    logger.info('Test log message');
 *    logger.error('Test error message');
 *    ```
 *
 * 9. **Security Best Practices**:
 *    - Never log sensitive data (passwords, tokens, PII)
 *    - Sanitize user input before logging
 *    - Set appropriate file permissions on log directory
 *    - Encrypt log files containing sensitive information
 *    - Implement log access controls
 *
 * 10. **Common Winston Modules to Consider**:
 *     - winston-mongodb: Store logs in MongoDB
 *     - winston-cloudwatch: Send logs to AWS CloudWatch
 *     - winston-slack: Send critical logs to Slack
 *     - winston-elasticsearch: Index logs in Elasticsearch
 */
