import winston from 'winston';
import { env } from '../config/env';

const consoleFormat = winston.format.combine(
  winston.format.colorize(),
  winston.format.printf(({ timestamp, level, message, ...meta }) => {
    const metaStr = Object.keys(meta).length ? ` ${JSON.stringify(meta)}` : '';
    return `${timestamp} [${level}]: ${message}${metaStr}`;
  })
);

const transports: winston.transport[] = [new winston.transports.Console()];

export const logger = winston.createLogger({
  level: env.NODE_ENV === 'production' ? 'info' : 'debug',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.errors({ stack: true }),
    env.NODE_ENV === 'production'
      ? winston.format.json()
      : consoleFormat
  ),
  transports,
});

// Add file transport in production (dynamic import to avoid breaking dev when not installed)
if (env.NODE_ENV === 'production') {
  import('winston-daily-rotate-file').then((mod) => {
    const DailyRotateFile = mod.default;
    logger.add(
      new DailyRotateFile({
        dirname: env.LOG_DIR,
        filename: 'api-%DATE%.log',
        datePattern: 'YYYY-MM-DD',
        maxSize: '20m',
        maxFiles: '14d',
        zippedArchive: true,
        format: winston.format.combine(
          winston.format.timestamp(),
          winston.format.errors({ stack: true }),
          winston.format.json(),
        ),
      })
    );
  }).catch(() => {
    logger.warn('winston-daily-rotate-file not installed, file logging disabled');
  });
}
