import winston from "winston";
import path from "path";
import { HttpStatusCode } from "../api/apiHelpers/HttpStatusCodes.js";

// Define log format
const logFormat = winston.format.combine(
    winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
    winston.format.errors({ stack: true }),
    winston.format.printf(({ timestamp, level, message, stack }) => {
        if (stack) {
            return `${timestamp} [${level.toUpperCase()}]: ${message}\n${stack}`;
        }
        return `${timestamp} [${level.toUpperCase()}]: ${message}`;
    })
);

// Create logs directory if it doesn't exist
const logsDir = path.join(process.cwd(), "logs");

// Create the logger
export const logger = winston.createLogger({
    level: process.env.LOG_LEVEL || "info",
    format: logFormat,
    transports: [
        // Console transport with colors
        new winston.transports.Console({
            format: winston.format.combine(
                winston.format.colorize(),
                logFormat
            ),
        }),

        // File transport for all logs
        new winston.transports.File({
            filename: path.join(logsDir, "combined.log"),
            maxsize: 5242880, // 5MB
            maxFiles: 5,
        }),

        // File transport for errors only
        new winston.transports.File({
            filename: path.join(logsDir, "error.log"),
            level: "error",
            maxsize: 5242880, // 5MB
            maxFiles: 5,
        }),
    ],
});

// Add request-specific logging helper
export const logRequest = (method: string, path: string, statusCode: number, duration: number) => {
    const message = `${method} ${path} ${statusCode} - ${duration}ms`;
    if (statusCode >= HttpStatusCode.INTERNAL_SERVER_ERROR) {
        logger.error(message);
    } else if (statusCode >= HttpStatusCode.BAD_REQUEST) {
        logger.warn(message);
    } else {
        logger.info(message);
    }
};

export default logger;