import fs from "fs";
import { createLogger, format, transports } from "winston";

const LOG_FILE = "logs/combined.log";

// Asegurarse de que la carpeta exista
if (!fs.existsSync("logs")) fs.mkdirSync("logs");

// Vaciar el archivo al iniciar
fs.writeFileSync(LOG_FILE, "", "utf-8");

const isDev = process.env.NODE_ENV !== "production";
const bold = "\x1b[1m";
const reset = "\x1b[0m";

const logger = createLogger({
    level: "info",
    format: format.combine(
        format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
        format.colorize(),
        !isDev
            ? format.printf(({ timestamp, level, message }) => {
                  return `[${timestamp}] ${level}: ${message}`;
              })
            : format.printf(({ timestamp, level, message }) => {
                  return ` ${level}: ${message}`;
              })
    ),
    transports: [
        new transports.Console(), // sigue mostrando en consola
        new transports.File({ filename: "logs/error.log", level: "error" }), // solo errores
        new transports.File({ filename: "logs/combined.log" }), // todos los logs
    ],
});

export const logIntent = (message: string) => {
    logger.info(`⏳ ${message}`);
};

export const logDone = (message: string) => {
    logger.info(`✅ ${bold}${message}${reset}`);
};

export const logError = (message: string, error: any) => {
    logger.info(`❌ ${bold}${message}${reset}\n\r`, error);
};

export const logWarn = (message: string) => {
    logger.info(`⚠️ ${message}`);
};

export const logDebug = (message: string) => {
    logger.debug(`${message}`);
};

export default logger;
