import { NextResponse } from 'next/server';

export async function GET() {
    const apiKey = "37eb7f83988cfd76ffb5c5af9adc25652efe5607e39997fc7d0e054d690ef25e";
    const placeId = "ChIJMzocvRE4K4gRg5HY6eu7Aek";

    let allReviews = [];
    let nextPageToken = null;

    try {
        let pageCount = 0;
        while (pageCount < 3) {
            pageCount++;
            const url = `https://serpapi.com/search.json?engine=google_maps_reviews&hl=en&api_key=${apiKey}&place_id=${placeId}${nextPageToken ? `&next_page_token=${nextPageToken}` : ""
                }`;

            const response = await fetch(url);
            const data = await response.json();

            if (data.error) {
                console.error("Pages API: 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;
            await new Promise((resolve) => setTimeout(resolve, 2500));
        }

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