const fs = require("fs");
const path = require("path");
const winston = require("winston");
const { getLogsDir, ensureDir } = require("./paths");

let logger;

function createLogger() {
  const logDir = getLogsDir();
  ensureDir(logDir);

  logger = winston.createLogger({
    level: process.env.LOG_LEVEL || "info",
    format: winston.format.combine(
      winston.format.timestamp(),
      winston.format.json(),
    ),
    transports: [
      new winston.transports.File({
        filename: path.join(logDir, "error.log"),
        level: "error",
        maxsize: 50 * 1024 * 1024,
        maxFiles: 10,
      }),
      new winston.transports.File({
        filename: path.join(logDir, "combined.log"),
        maxsize: 50 * 1024 * 1024,
        maxFiles: 10,
      }),
    ],
  });

  if (process.env.NODE_ENV !== "production") {
    logger.add(
      new winston.transports.Console({
        format: winston.format.combine(
          winston.format.colorize(),
          winston.format.simple(),
        ),
      }),
    );
  } else if (
    process.platform === "win32" &&
    process.env.SIRAYA_WINDOWS_SERVICE === "1"
  ) {
    logger.add(
      new winston.transports.Console({
        level: "info",
        format: winston.format.combine(
          winston.format.timestamp(),
          winston.format.simple(),
        ),
      }),
    );
  }

  return logger;
}

function getLogger() {
  if (!logger) return createLogger();
  return logger;
}

module.exports = { createLogger, getLogger };
