import { Request, Response, NextFunction } from "express";
import { logger, logRequest } from "../utils/logger.js";

/**
 * Middleware to log all incoming requests and their responses
 * Logs: method, path, status code, response time, and user info
 */
export const requestLoggerMiddleware = (
    req: Request,
    res: Response,
    next: NextFunction
) => {
    const startTime = Date.now();

    // Get the full URL path (baseUrl + path)
    const fullPath = req.baseUrl + req.path;

    // Log incoming request
    const userId = req.currentUser?.id || "anonymous";
    logger.info(`→ ${req.method} ${fullPath} (User: ${userId})`);

    // Capture the original res.json and res.send to log response
    const originalJson = res.json.bind(res);
    const originalSend = res.send.bind(res);

    // Override res.json
    res.json = function (body: any) {
        const duration = Date.now() - startTime;
        logRequest(req.method, fullPath, res.statusCode, duration);
        return originalJson(body);
    };

    // Override res.send
    res.send = function (body: any) {
        const duration = Date.now() - startTime;
        logRequest(req.method, fullPath, res.statusCode, duration);
        return originalSend(body);
    };

    // Handle responses that end without json/send
    res.on("finish", () => {
        // Only log if we haven't already logged (json/send weren't called)
        if (!res.headersSent) {
            const duration = Date.now() - startTime;
            logRequest(req.method, fullPath, res.statusCode, duration);
        }
    });

    next();
};