export const dynamic = "force-dynamic"; // ✅ Ensures the route is treated as dynamic

export async function GET(req) {
    const { searchParams } = new URL(req.url);
    const domain = searchParams.get("domain");
    const endpoint = searchParams.get("endpoint");

    if (!domain || !endpoint) {
        return new Response(JSON.stringify({ error: "Domain and endpoint are required" }), {
            status: 400,
            headers: { "Content-Type": "application/json" },
        });
    }

    try {
        // Construct the external API URL
        const baseEndpoint = endpoint.split("?")[0]; // Remove query params from endpoint
        const externalUrl = new URL(`https://nestapp.adhcloud.space/${baseEndpoint}`);
        
        // Add domain and query parameters
        const params = new URLSearchParams(endpoint.split("?")[1]);
        params.set("domain", domain); // Ensure domain is correctly set
        externalUrl.search = params.toString();

        // Fetch data from the external API
        const response = await fetch(externalUrl.toString());
        if (!response.ok) {
            const errorText = await response.text();
            console.error(`External API Error: ${response.status} - ${errorText}`);
            throw new Error(`HTTP Error: ${response.status}`);
        }

        const data = await response.json();
        return new Response(JSON.stringify(data), {
            status: 200,
            headers: { "Content-Type": "application/json" },
        });
    } catch (error) {
        console.error("Error in /api/proxy:", error);
        return new Response(JSON.stringify({ error: error.message }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
        });
    }
}
