import { fallbackGoogleReviews } from '@/lib/reviewUtils';

export const dynamic = 'force-static';

const SERPAPI_URL = 'https://serpapi.com/search.json?engine=google_maps_reviews&hl=en';

async function fetchGoogleReviews(apiKey, placeId) {
  if (!apiKey || !placeId) {
    throw new Error('Missing SERPAPI_KEY or SERPAPI_PLACE_ID');
  }

  const url = `${SERPAPI_URL}&api_key=${encodeURIComponent(apiKey)}&place_id=${encodeURIComponent(placeId)}`;
  const response = await fetch(url);

  if (!response.ok) {
    const body = await response.text().catch(() => '');
    throw new Error(`SerpAPI request failed ${response.status} ${response.statusText}: ${body}`);
  }

  const data = await response.json();

  if (data.error) {
    throw new Error(data.error.message || data.error);
  }

  if (!Array.isArray(data.reviews)) {
    throw new Error('SerpAPI returned no reviews array');
  }

  return data.reviews;
}

export async function GET() {
  const apiKey = process.env.SERPAPI_KEY;
  const placeId = process.env.SERPAPI_PLACE_ID;

  try {
    const reviews = await fetchGoogleReviews(apiKey, placeId);
    return new Response(JSON.stringify({ reviews, total: reviews.length }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' },
    });
  } catch (error) {
    console.error('Reviews API error:', error);
    return new Response(
      JSON.stringify({
        reviews: fallbackGoogleReviews,
        total: fallbackGoogleReviews.length,
        fallback: true,
        error: error.message,
      }),
      {
        status: 200,
        headers: { 'Content-Type': 'application/json' },
      }
    );
  }
}
