import { NextResponse } from 'next/server';

export async function GET() {
    const apiKey = "8f20ae2ffd1700f38274ea87d2230ea8e0982834f8376bf311e7a4f5092662a8";
    const placeId = "ChIJW9-CDf_X1IkRnBCKKZdqyvA";

    let allReviews: any[] = [];
    let nextPageToken = null;

    try {
        let pageCount = 0;
        // Fetch up to 10 pages of reviews to get "all" reviews
        while (pageCount < 10) {
            pageCount++;
            const url: string = `https://serpapi.com/search.json?engine=google_maps_reviews&hl=en&api_key=${apiKey}&place_id=${placeId}${nextPageToken ? `&next_page_token=${nextPageToken}` : ""
                }`;

            const response: Response = await fetch(url, { cache: 'no-store' });
            const data: any = await response.json();

            if (data.error) {
                console.error("API Route: SerpAPI Error:", data.error);
                break;
            }

            if (data.reviews && data.reviews.length > 0) {
                allReviews = [...allReviews, ...data.reviews];
            } else {
                break;
            }

            if (!data.serpapi_pagination || !data.serpapi_pagination.next_page_token) {
                break;
            }

            nextPageToken = data.serpapi_pagination.next_page_token;
            // Respect API rate limits/throttling if needed, but for 3 pages it's usually fine.
            // Small delay to be safe
            await new Promise((resolve) => setTimeout(resolve, 500));
        }

        return NextResponse.json({ reviews: allReviews, total: allReviews.length });
    } catch (error: any) {
        console.error("API Route: Unexpected Error:", error);
        return NextResponse.json({ error: "Failed to fetch reviews", details: error.message }, { status: 500 });
    }
}
