import { blogData } from "./constant";

export interface Review {
    text?: string;
    description?: string;
    snippet?: string;
    review_text?: string;
    body?: string;
    content?: string;
    rating: number;
    profile_photo_url?: string;
    author_profile_photo_url?: string;
    user?: {
        thumbnail?: string;
        name?: string;
    };
    author_name?: string;
}

export async function getReviews(): Promise<Review[]> {
    const apiKey = "37eb7f83988cfd76ffb5c5af9adc25652efe5607e39997fc7d0e054d690ef25e";
    const placeId = "ChIJJU4PkTL1K4gRPSWJdlAQ7ko";

    let allReviews: Review[] = [];
    let nextPageToken: string | null = null;
    let pageCount = 0;

    try {
        while (pageCount < 3) {
            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 = await fetch(url, { next: { revalidate: 3600 } });

            if (!response.ok) {
                break;
            }

            const data = await response.json();

            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;
            // No need for delay on server fetch unless we are worried about rate limiting, 
            // but Next.js will cache this.
        }

        const cleaned = allReviews.filter((r: Review) =>
            (r.text || r.description || r.snippet || r.review_text || r.body || r.content) &&
            r.rating >= 4
        );

        return cleaned;
    } catch (error) {
        console.error("Failed to fetch reviews on server:", error);
        return [];
    }
}
