// apps/api/src/utils/logger.js

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

class Logger {
    constructor() {
        this.logDir = path.join(__dirname, '../../../storage/logs');
        this.ensureLogDir();
    }
    
    ensureLogDir() {
        if (!fs.existsSync(this.logDir)) {
            fs.mkdirSync(this.logDir, { recursive: true });
        }
    }
    
    getLogFilePath() {
        const date = new Date().toISOString().split('T')[0];
        return path.join(this.logDir, `app-${date}.log`);
    }
    
    formatMessage(level, message, meta = {}) {
        const timestamp = new Date().toISOString();
        const metaStr = Object.keys(meta).length ? JSON.stringify(meta) : '';
        return `[${timestamp}] ${level}: ${message} ${metaStr}`.trim();
    }
    
    write(level, message, meta = {}) {
        const formatted = this.formatMessage(level, message, meta);
        console.log(formatted);
        
        if (process.env.NODE_ENV === 'production') {
            fs.appendFileSync(this.getLogFilePath(), formatted + '\n');
        }
    }
    
    info(message, meta = {}) {
        this.write('INFO', message, meta);
    }
    
    warn(message, meta = {}) {
        this.write('WARN', message, meta);
    }
    
    error(message, meta = {}) {
        this.write('ERROR', message, meta);
    }
    
    debug(message, meta = {}) {
        if (process.env.NODE_ENV === 'development') {
            this.write('DEBUG', message, meta);
        }
    }
    
    http(req, res, responseTime) {
        const message = `${req.method} ${req.url} ${res.statusCode} - ${responseTime}ms`;
        this.info(message, {
            method: req.method,
            url: req.url,
            status: res.statusCode,
            responseTime,
            ip: req.ip
        });
    }
}

module.exports = new Logger();