import { NextRequest, NextResponse } from 'next/server';
import axios from 'axios';

export async function GET(req: NextRequest) {
    const { pathname, search } = new URL(req.url);
    const path = pathname.replace('/api/hestia', '');
    const targetUrl = `https://api.hestiacp.metatronhost.com${path}${search}`;

    try {
        const response = await axios.get(targetUrl, {
            headers: {
                // Forward relevant headers if needed, but for now just basic GET
                'Accept': 'application/json',
            },
        });

        return NextResponse.json(response.data);
    } catch (error: any) {
        console.error(`Proxy error for ${targetUrl}:`, error.message);
        return NextResponse.json(
            {
                message: 'Failed to fetch from Hestia API',
                error: error.message,
                details: error.response?.data
            },
            { status: error.response?.status || 500 }
        );
    }
}

export async function POST(req: NextRequest) {
    const { pathname } = new URL(req.url);
    const path = pathname.replace('/api/hestia', '');
    const targetUrl = `https://api.hestiacp.metatronhost.com${path}`;

    try {
        const body = await req.json();
        const response = await axios.post(targetUrl, body, {
            headers: {
                'Content-Type': 'application/json',
            },
        });

        return NextResponse.json(response.data);
    } catch (error: any) {
        console.error(`Proxy POST error for ${targetUrl}:`, error.message);
        return NextResponse.json(
            {
                message: 'Failed to post to Hestia API',
                error: error.message,
                details: error.response?.data
            },
            { status: error.response?.status || 500 }
        );
    }
}
