const winston = require('winston');
const path = require('path');
const fs = require('fs');

const transports = [
  new winston.transports.Console({
    format: winston.format.combine(
      winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
      winston.format.errors({ stack: true }),
      winston.format.simple()
    ),
  }),
];

// File logging hanya jika bukan Railway (ada folder logs)
const logDir = path.join(__dirname, '../../logs');
try {
  if (!fs.existsSync(logDir)) fs.mkdirSync(logDir, { recursive: true });
  transports.push(new winston.transports.File({ filename: path.join(logDir, 'error.log'), level: 'error' }));
  transports.push(new winston.transports.File({ filename: path.join(logDir, 'combined.log') }));
} catch (e) {
  // skip file logging jika tidak bisa buat folder
}

const logger = winston.createLogger({
  level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
  format: winston.format.combine(
    winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
    winston.format.errors({ stack: true }),
    winston.format.json()
  ),
  transports,
});

module.exports = logger;
