const path = require('path');
const winston = require('winston');
require('winston-daily-rotate-file');

const fileTransport = new winston.transports.DailyRotateFile({
  filename: path.join(process.cwd(), 'logs/easytransport-%DATE%.log'),
  datePattern: 'DDMMYYYY',
  zippedArchive: true,
  maxSize: '20m',
  maxFiles: '14d'
});

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.combine(
    winston.format.timestamp({ format: 'DD-MM-YYYY HH:mm:ss' }),
    winston.format.printf(info => {
      const message = typeof info.message === 'object' ?
        JSON.stringify(info.message, null, 2) :
        info.message;
      return `[${info.level}][${info.timestamp}] ${message}`;
    })
  ),
  transports: [
    new winston.transports.Console({
      format: winston.format.combine(
        winston.format.colorize(),
        winston.format.printf(info => {
          const message = typeof info.message === 'object' ?
            JSON.stringify(info.message, null, 2) :
            info.message;
          return `[${info.level}][${info.timestamp}] ${message}`;
        })
      )
    }),
    fileTransport
  ]
});

if (process.env.NODE_ENV !== 'production') {
  logger.level = 'debug';
}

module.exports = {
  log: function (level, message, error = null, matricule = null) {
    const formattedMessage = error ? `${message} : ${error.message}` : message;

    logger.log({
      level,
      message: matricule ? `[${matricule}] ${formattedMessage}` : formattedMessage,
    });
  }
};
