/**
 * Logger Utility
 * Centralized logging utility for the application
 */

// Import winston for structured logging
const winston = require('winston');
// Import app configuration
const appConfig = require('../config/app');

// Define log format
const logFormat = winston.format.combine(
  winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), // Add timestamp
  winston.format.errors({ stack: true }), // Include error stack traces
  winston.format.splat(), // Support for string interpolation
  winston.format.json() // JSON format for structured logging
);

// Console format for development (more readable)
const consoleFormat = winston.format.combine(
  winston.format.colorize(), // Add colors to console output
  winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
  winston.format.printf(({ level, message, timestamp, ...metadata }) => {
    // Format log message with timestamp and metadata
    let msg = `${timestamp} [${level}]: ${message}`;
    if (Object.keys(metadata).length > 0) {
      msg += ` ${JSON.stringify(metadata)}`;
    }
    return msg;
  })
);

// Create winston logger instance
const logger = winston.createLogger({
  level: appConfig.logging.level, // Set log level from config
  format: logFormat, // Use log format
  defaultMeta: { service: 'xyz-pos-server' }, // Default metadata
  transports: [
    // Write all logs to console
    new winston.transports.Console({
      format: process.env.NODE_ENV === 'production' ? logFormat : consoleFormat,
    }),
    // Write all logs with level 'error' and below to error.log
    new winston.transports.File({ 
      filename: 'logs/error.log', 
      level: 'error',
      maxsize: 5242880, // 5MB
      maxFiles: 5, // Keep 5 rotated files
    }),
    // Write all logs to combined.log
    new winston.transports.File({ 
      filename: 'logs/combined.log',
      maxsize: 5242880, // 5MB
      maxFiles: 5, // Keep 5 rotated files
    }),
  ],
});

// If we're not in production, log to console with simpler format
if (process.env.NODE_ENV !== 'production') {
  logger.add(new winston.transports.Console({
    format: consoleFormat,
  }));
}

// Export logger instance
module.exports = logger;

