import winston from 'winston';
import DailyRotateFile from 'winston-daily-rotate-file';
import { env } from './env.js';

const isProduction = env.NODE_ENV === 'production';

const fileFormat = winston.format.combine(
  winston.format.timestamp(),
  winston.format.errors({ stack: true }),
  winston.format.json(),
);

const consoleFormat = winston.format.combine(
  winston.format.colorize(),
  winston.format.timestamp({ format: 'HH:mm:ss' }),
  winston.format.printf(({ timestamp, level, message, ...meta }) => {
    delete meta[Symbol.for('splat')];
    const extra = Object.keys(meta).length ? ` ${JSON.stringify(meta)}` : '';
    return `${timestamp} ${level}: ${message}${extra}`;
  }),
);

// Logger stays at 'http' level so every request (and every 4xx/5xx) always
// reaches the log files, even in production where the console stays quiet.
const logger = winston.createLogger({
  level: 'http',
  levels: winston.config.npm.levels,
  format: fileFormat,
  transports: [
    new DailyRotateFile({
      dirname: 'logs',
      filename: 'combined-%DATE%.log',
      datePattern: 'YYYY-MM-DD',
      maxFiles: '14d',
      level: 'http',
    }),
    new DailyRotateFile({
      dirname: 'logs',
      filename: 'error-%DATE%.log',
      datePattern: 'YYYY-MM-DD',
      maxFiles: '30d',
      level: 'error',
    }),
    new winston.transports.Console({
      level: isProduction ? 'info' : 'http',
      format: isProduction ? fileFormat : consoleFormat,
    }),
  ],
});

export default logger;
