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

// Create the log directory if it doesn't exist
const logDirectory = path.join(__dirname, "logs");
if (!fs.existsSync(logDirectory)) {
  fs.mkdirSync(logDirectory);
}

// Define the log levels and colors
const logLevels = {
  error: 0,
  warn: 1,
  info: 2,
  debug: 3,
};

// Configure the Winston logger
const logger = winston.createLogger({
  levels: logLevels,
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.printf(({ level, message, timestamp }) => {
      const formattedTimestamp = timestamp.slice(0, 19).replace("T", " ");
      return `[${formattedTimestamp}] ${level
        .toUpperCase()
        .padEnd(5)} : ${message}`;
    })
  ),
  transports: [
    new winston.transports.Console({
      level: "info",
      format: winston.format.combine(
        winston.format.colorize({ all: true }),
        winston.format.simple(),
        winston.format.printf(({ level, message, timestamp }) => {
          const formattedTimestamp = timestamp.slice(0, 19).replace("T", " ");
          return `[${formattedTimestamp}] ${level
            .toUpperCase()
            .padEnd(5)} : ${message}`;
        })
      ),
    }),
    new winston.transports.File({
      filename: path.join(logDirectory, "app.log"),
      level: "debug",
    }),
  ],
});

// Export the configured logger
module.exports = logger;
