/* eslint-disable @typescript-eslint/no-unused-vars */
import rTracer from "cls-rtracer";
import path from "path";
import { createLogger, format, transports } from "winston";
import DailyRotateFile from "winston-daily-rotate-file";
import { config } from "../../config";

export const initLogger = (rTracer) => {
  // a custom format that outputs request id

  const consoleFormat = format.combine(
    format.colorize(),
    format.timestamp(),
    format.align(),
    format.splat(),
    format.printf((info) => {
      const rid = rTracer.id();

      let out =
        config.isProduction && rid
          ? `${info.timestamp} [request-id:${rid}] - ${info.level}: [${info.label}]: ${info.message}`
          : `${info.timestamp} - ${info.level}:  [${info.label}]: ${info.message}`;

      if (info.metadata?.error) {
        out = `${out} ${info.metadata.error}`;
        if (info.metadata?.error?.stack) {
          out = `${out} ${info.metadata.error.stack}`;
        }
      }

      return out;
    })
  );

  const fileFormat = format.combine(
    format.timestamp(),
    format.splat(),
    format.label({ label: path.basename(String(require.main?.filename)) }),
    //format.metadata(),
    format.metadata({ fillExcept: ["message", "level", "timestamp", "label"] }),
    format.simple(),
    format.json()
  );

  const logger = createLogger({
    level: config.isProduction ? "debug" : "debug",

    format: fileFormat,

    transports: [
      new DailyRotateFile({
        dirname: config.isProduction ? "/logs" : ".",
        filename: "error-%DATE%.log",
        datePattern: "YYYY-MM-DD",
        utc: true,
        level: "error",
        maxSize: "5m",
        maxFiles: "1d",
      }),
      new DailyRotateFile({
        dirname: config.isProduction ? "/logs" : ".",
        filename: "debug-%DATE%.log",
        datePattern: "YYYY-MM-DD",
        utc: true,
        level: "debug",
        maxSize: "5m",
        maxFiles: "1d",
      }),
    ],
  });

  //
  // If we're not in production then log to the `console` with the format:
  // `${info.level}: ${info.message} JSON.stringify({ ...rest }) `
  //
  //if (!config.isProduction) {
  logger.add(
    new transports.Console({
      format: consoleFormat,
      level: "debug",
    })
  );
  //}

  return logger;
};

export const logger = () => {
  return initLogger(rTracer);
};
