import winston from 'winston';
import path from 'path';
import fs from 'fs-extra';

export const logger = winston.createLogger({
  level: process.env.LOG_LEVEL || 'info',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.errors({ stack: true }),
    winston.format.json()
  ),
  transports: [
    new winston.transports.Console({
      format: winston.format.combine(
        winston.format.colorize(),
        winston.format.printf(({ timestamp, level, message, ...meta }) => {
          let msg = `${timestamp} [${level}]: ${message}`;
          if (Object.keys(meta).length > 0) {
            msg += ` ${JSON.stringify(meta)}`;
          }
          return msg;
        })
      ),
    }),
  ],
});

// Add file transport if configured
if (process.env.LOG_FILE) {
  const logDir = path.dirname(process.env.LOG_FILE);
  fs.ensureDirSync(logDir);

  logger.add(new winston.transports.File({
    filename: process.env.LOG_FILE,
    maxsize: 10 * 1024 * 1024, // 10MB
    maxFiles: 5,
  }));
}
