const axios = require('axios');

const requestHandler = async (req, res, next) => {
    console.log("Incoming Request Path:", req.path);
    console.log("Request Method:", req.method);
    console.log("Request Body:", req.body);

    // Capture the original request details
    const originalUrl = `${req.protocol}://${req.get('host')}${req.originalUrl}`;
    // const originalUrl = req.path;
    const requestData = req.body; // If there's a request body

    // console.log(originalUrl, requestData)
    try {
        // Forward the request to the original destination
        const response = await axios({
            method: req.method, // Forward the original request method (GET, POST, etc.)
            url: originalUrl, // Use the same endpoint
            data: requestData, // Pass request data (if any)
            headers: req.headers, // Forward headers
        });
        // console.log(response)
        console.log("Response from destination:", response.data);

        // Send back the response to the client
        return res.status(response.status).json(response.data);
    } catch (error) {
        console.error("Error forwarding request:", error.message);
        return res.status(error.response?.status || 500).json({
            error: "Failed to process request",
            details: error.message
        });
    }
};

module.exports = requestHandler;
