const express = require("express");
const axios = require("axios");
const router = express.Router();

// Block private/internal IP ranges to prevent SSRF
const SSRF_BLOCKED = [
    /^localhost$/i,
    /^127\./,
    /^10\./,
    /^172\.(1[6-9]|2\d|3[01])\./,
    /^192\.168\./,
    /^::1$/,
    /^0\.0\.0\.0/,
    /^169\.254\./, // link-local
    /^fd[0-9a-f]{2}:/i, // IPv6 ULA
];

function isSafeUrl(urlString) {
    let parsed;
    try {
        parsed = new URL(urlString);
    } catch {
        return false;
    }

    if (!["http:", "https:"].includes(parsed.protocol)) return false;

    const hostname = parsed.hostname;
    return !SSRF_BLOCKED.some((pattern) => pattern.test(hostname));
}

/**
 * POST /api/proxy
 * Body:
 *   url      {string}  required  - The external API URL to call
 *   method   {string}  optional  - HTTP method (default: GET)
 *   headers  {object}  optional  - Headers to forward
 *   data     {any}     optional  - Request body to forward
 */
router.post("/", async (req, res, next) => {
    const { url, method = "GET", headers = {}, data } = req.body;

    if (!url) {
        return res.status(400).json({ success: false, message: "url is required in request body" });
    }

    if (!isSafeUrl(url)) {
        return res.status(400).json({ success: false, message: "Invalid or disallowed URL" });
    }

    try {
        const response = await axios({
            method: method.toUpperCase(),
            url,
            headers,
            data,
            timeout: 10000,
        });

        res.status(200).json({
            success: true,
            status: response.status,
            headers: response.headers,
            data: response.data,
        });
    } catch (err) {
        if (err.response) {
            // External API returned an error response
            return res.status(502).json({
                success: false,
                message: "External API error",
                status: err.response.status,
                data: err.response.data,
            });
        }
        next(err);
    }
});

module.exports = router;
