const fs = require('fs');
const path = require('path');

// Create logs directory if it doesn't exist
const logsDir = path.join(__dirname, '..', 'logs');
if (!fs.existsSync(logsDir)) {
    fs.mkdirSync(logsDir, { recursive: true });
}

// Log file path
const errorLogPath = path.join(logsDir, 'error.log');
const appLogPath = path.join(logsDir, 'app.log');

/**
 * Format timestamp for log entries
 */
function getTimestamp() {
    return new Date().toISOString();
}

/**
 * Write to log file
 */
function writeToFile(filePath, message) {
    try {
        const logEntry = `[${getTimestamp()}] ${message}\n`;
        fs.appendFileSync(filePath, logEntry, { encoding: 'utf8' });
    } catch (err) {
        // Fallback to console if file write fails
        console.error(`Failed to write to log file: ${err.message}`);
        console.error(`Original message: ${message}`);
    }
}

/**
 * Logger utility
 */
const logger = {
    /**
     * Log error messages
     */
    error: (message, error = null) => {
        let logMessage = `[ERROR] ${message}`;
        
        if (error) {
            if (error instanceof Error) {
                logMessage += `\n  Message: ${error.message}`;
                logMessage += `\n  Stack: ${error.stack}`;
            } else {
                logMessage += `\n  Details: ${JSON.stringify(error, null, 2)}`;
            }
        }
        
        // Write to error log file
        writeToFile(errorLogPath, logMessage);
        
        // Also write to app log
        writeToFile(appLogPath, logMessage);
        
        // Also output to console for immediate visibility
        console.error(logMessage);
    },

    /**
     * Log warning messages
     */
    warn: (message, data = null) => {
        let logMessage = `[WARN] ${message}`;
        
        if (data) {
            logMessage += `\n  Details: ${JSON.stringify(data, null, 2)}`;
        }
        
        writeToFile(appLogPath, logMessage);
        console.warn(logMessage);
    },

    /**
     * Log info messages
     */
    info: (message, data = null) => {
        let logMessage = `[INFO] ${message}`;
        
        if (data) {
            logMessage += `\n  Details: ${JSON.stringify(data, null, 2)}`;
        }
        
        writeToFile(appLogPath, logMessage);
        console.log(logMessage);
    },

    /**
     * Log debug messages (only if NODE_ENV is not production)
     */
    debug: (message, data = null) => {
        if (process.env.NODE_ENV === 'production') {
            return;
        }
        
        let logMessage = `[DEBUG] ${message}`;
        
        if (data) {
            logMessage += `\n  Details: ${JSON.stringify(data, null, 2)}`;
        }
        
        writeToFile(appLogPath, logMessage);
        console.log(logMessage);
    },

    /**
     * Log uncaught exceptions
     */
    logUncaughtException: (error) => {
        const logMessage = `[UNCAUGHT EXCEPTION] Application crashed\n  Message: ${error.message}\n  Stack: ${error.stack}`;
        writeToFile(errorLogPath, logMessage);
        writeToFile(appLogPath, logMessage);
        console.error(logMessage);
    },

    /**
     * Log unhandled promise rejections
     */
    logUnhandledRejection: (reason, promise) => {
        let logMessage = `[UNHANDLED REJECTION] Promise rejection was not handled\n`;
        
        if (reason instanceof Error) {
            logMessage += `  Message: ${reason.message}\n  Stack: ${reason.stack}`;
        } else {
            logMessage += `  Reason: ${JSON.stringify(reason, null, 2)}`;
        }
        
        writeToFile(errorLogPath, logMessage);
        writeToFile(appLogPath, logMessage);
        console.error(logMessage);
    },

    /**
     * Get log file paths
     */
    getLogPaths: () => ({
        errorLog: errorLogPath,
        appLog: appLogPath
    })
};

module.exports = logger;

