export async function GET() {
  const apiKey = "37eb7f83988cfd76ffb5c5af9adc25652efe5607e39997fc7d0e054d690ef25e";
  const placeId = "ChIJc-0YDrs9K4gRyZNjbj14s70";

  let allReviews = [];
  let nextPageToken = null;

  try {
    while (true) {
      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.reviews && data.reviews.length > 0) {
        allReviews = [...allReviews, ...data.reviews];
      }

      // Stop if no next page
      if (!data.serpapi_pagination || !data.serpapi_pagination.next_page_token) {
        break;
      }

      nextPageToken = data.serpapi_pagination.next_page_token;

      // SerpAPI requires 2–3 seconds delay before using next_page_token
      await new Promise((resolve) => setTimeout(resolve, 2500));
    }

    return new Response(
      JSON.stringify({ reviews: allReviews, total: allReviews.length }),
      {
        status: 200,
        headers: { "Content-Type": "application/json" },
      }
    );
  } catch (error) {
    console.error(error);
    return new Response(JSON.stringify({ error: "Failed to fetch reviews" }), {
      status: 500,
      headers: { "Content-Type": "application/json" },
    });
  }
}
