import { NextResponse } from 'next/server';

// Required for Next.js static export (output: 'export' in next.config.ts)
export const dynamic = 'force-static';
export const revalidate = 3600; // Re-fetch at most every hour

export async function GET() {
    const apiKey = "37eb7f83988cfd76ffb5c5af9adc25652efe5607e39997fc7d0e054d690ef25e";
    // VG Fence Products, Ayr, ON - data_id from Google Maps
    const dataId = "0x0:0xd39d64a69ab32c65";

    try {
        const url = `https://serpapi.com/search.json?engine=google_maps_reviews&hl=en&api_key=${apiKey}&data_id=${dataId}`;

        const response = await fetch(url);

        if (!response.ok) {
            const errorText = await response.text();
            console.error(`SerpAPI error! Status: ${response.status}, Body: ${errorText}`);
            return NextResponse.json({
                error: "SerpAPI Error",
                status: response.status,
                message: errorText
            }, { status: 500 });
        }

        const data = await response.json();

        if (data.error) {
            console.error("SerpAPI Data Error:", data.error);
            return NextResponse.json({ error: data.error }, { status: 500 });
        }

        // Normalize reviews to a consistent shape regardless of SerpAPI field names
        const rawReviews = data.reviews || [];
        // Return ALL reviews – let the UI filter if needed
        const reviews = rawReviews.map((r: any) => ({
            name: r.user?.name || r.username || "Customer",
            rating: r.rating || 5,
            text: r.snippet || r.extracted_snippet?.original || r.description || "",
            date: r.date || r.iso_date || "",
            profilePhoto: r.user?.thumbnail || r.user_thumbnail || null,
            reviewLink: r.link || null,
        }));

        return NextResponse.json({
            reviews,
            total: reviews.length,
            place: data.place_info || null,
        });

    } catch (error: any) {
        console.error("Critical error in /api/google-reviews:", error);
        return NextResponse.json({
            error: "Internal Server Error",
            message: error.message,
        }, { status: 500 });
    }
}
