import { NextResponse } from 'next/server';

export const dynamic = 'force-static';
export const revalidate = 3600; // Cache for 1 hour during build/dev

interface SerpReview {
    text?: string;
    rating: number;
    [key: string]: any;
}

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

    let allReviews: SerpReview[] = [];
    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}` : ""}`;
            console.log(`API: Fetching Page ${pageCount} from URL: ${url.replace(apiKey, "HIDDEN")}`);

            const response: Response = await fetch(url);

            if (!response.ok) {
                const errorText = await response.text();
                console.error(`API: SerpAPI fetch failed with status ${response.status}:`, errorText.slice(0, 200));
                // If the first page fails, we should report it in the response
                if (pageCount === 1) {
                    return NextResponse.json({ error: "SerpAPI Fetch Failed", status: response.status, details: errorText.slice(0, 200) }, { status: response.status });
                }
                break;
            }

            const data: { reviews?: SerpReview[]; error?: string; serpapi_pagination?: { next_page_token?: string } } = await response.json();

            if (data.error) {
                console.error("API: SerpAPI JSON Error:", data.error);
                if (pageCount === 1) {
                    return NextResponse.json({ error: "SerpAPI Error", details: data.error }, { status: 400 });
                }
                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, 200));
        }

        return NextResponse.json({ reviews: allReviews, total: allReviews.length });
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : String(error);
        const stack = error instanceof Error ? error.stack : "";
        console.error("API: Unexpected Server Error:", message, stack);
        return NextResponse.json({ error: "Failed to fetch reviews", details: message, stack: stack?.slice(0, 200) }, { status: 500 });
    }
}
