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

export async function POST(request: NextRequest) {
    try {
        const apiKey = process.env.GOOGLE_GEMINI_API_KEY;
        const apiUrl = process.env.GEMINI_API_URL;

        if (!apiKey || !apiUrl) {
            return NextResponse.json(
                { error: { message: "AI API configuration is missing on server." } },
                { status: 500 }
            );
        }

        const body = await request.json();
        const url = `${apiUrl}?key=${apiKey}`;

        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(body),
        });

        const data = await response.json();

        if (!response.ok) {
            return NextResponse.json(
                { error: { message: data?.error?.message || "AI generation failed." } },
                { status: response.status }
            );
        }

        return NextResponse.json(data);
    } catch (error: any) {
        console.error("AI Proxy Error:", error);
        return NextResponse.json(
            { error: { message: error.message || "Internal server error." } },
            { status: 500 }
        );
    }
}
