import winston from 'winston';
import DailyRotateFile from 'winston-daily-rotate-file';

const { createLogger, format, transports } = winston;
const { combine, timestamp, label, printf } = format;


const myFormatFile = printf((info) => {
  const { level, message, timestamp, ...meta } = info;
  const label = meta.label || 'toto';
  delete meta.label; // pour ne pas le répéter dans le JSON
  const base = `${timestamp} ${level} [${label}] ${message}`;

  const metaString = Object.keys(meta).length ? ` ${JSON.stringify(meta)}` : '';
  return base + metaString;
});

const myFormatConsole = printf(({ level, message, label, timestamp }) => {
  return `${timestamp} ${level} [${label}] ${message}`;
});



const logger = winston.createLogger({
  //level: 'info',
  format: combine(
    timestamp({format: 'YYYY-MM-DD HH:mm:ss'}),
    myFormatFile
  ),
  defaultMeta: { service: 'user-service' },
  transports: [
    new DailyRotateFile({
        dirname: 'logs',
        filename: 'log_global-%DATE%.log',
        datePattern: 'YYYY-MM-DD',
        zippedArchive: true,
        maxFiles: '14d',
        }),
  ],
  exceptionHandlers: [
    new DailyRotateFile({
        dirname: 'logs',
        filename: 'log_global-%DATE%.log',
        datePattern: 'YYYY-MM-DD',
        zippedArchive: true,
        maxFiles: '14d',
        }),
    new winston.transports.Console()
  ],
  rejectionHandlers: [
    new DailyRotateFile({
        dirname: 'logs',
        filename: 'log_global-%DATE%.log',
        datePattern: 'YYYY-MM-DD',
        zippedArchive: true,
        maxFiles: '14d',
        }),
    new winston.transports.Console()
  ]
});




if (process.env.ENV !== 'production' ) {
  logger.add(new winston.transports.Console(
    {
      format: combine(
        label({ label: '' }),
        timestamp({format: 'YYYY-MM-DD HH:mm:ss'}),
        myFormatConsole
      ),
    handleExceptions: true //pour afficher également les exceptions dans la console
    })
  );
}

/////////////////////////////////////////////////
// EXPORT DE MODULE POUR QU'IL SOIT LU DANS LES AUTRES FICHIERS JS
/////////////////////////////////////////////////
export default logger;