const asyncHandler = require("express-async-handler");

const logActivity = asyncHandler(async (req, res, next) => {
    const startTime = Date.now();
    
    // Log request details
    console.log('\n🚀 API Request:', {
        timestamp: new Date().toISOString(),
        method: req.method,
        url: `${req.baseUrl}${req.path}`,
        fullUrl: `${req.protocol}://${req.get('host')}${req.originalUrl}`,
        headers: {
            'user-agent': req.get('user-agent'),
            'authorization': req.get('authorization') ? 'Bearer [HIDDEN]' : 'None',
            'content-type': req.get('content-type'),
            'origin': req.get('origin')
        },
        query: Object.keys(req.query).length > 0 ? req.query : 'None',
        body: req.body && Object.keys(req.body).length > 0 ? req.body : 'None',
        ip: req.ip || req.connection.remoteAddress
    });

    // Override res.end to log response details
    const originalEnd = res.end;
    res.end = function(chunk, encoding) {
        const duration = Date.now() - startTime;
        
        console.log('✅ API Response:', {
            timestamp: new Date().toISOString(),
            method: req.method,
            url: `${req.baseUrl}${req.path}`,
            statusCode: res.statusCode,
            statusMessage: res.statusMessage,
            duration: `${duration}ms`,
            responseHeaders: res.getHeaders()
        });
        
        console.log('─'.repeat(80)); // Separator line
        
        originalEnd.call(this, chunk, encoding);
    };

    next();
});

module.exports = logActivity;