const axios = require("axios");
const AppError = require("../utils/appError");

// Helper to catch async errors (if you don't have a specific catchAsync util, use this wrapper)
const catchAsync = (fn) => {
  return (req, res, next) => {
    fn(req, res, next).catch(next);
  };
};

exports.getGoogleReviews = catchAsync(async (req, res, next) => {
  const { placeId } = req.query;

  if (!placeId) {
    return next(new AppError("Please provide a Google Place ID", 400));
  }

  const apiKey = process.env.GOOGLE_PLACES_API_KEY;

  if (!apiKey) {
    return next(
      new AppError("Server configuration error: API Key missing", 500),
    );
  }

  try {
    // We request specific fields: 'reviews' (and optionally 'rating', 'user_ratings_total')
    // to keep the payload small and relevant.
    const googleResponse = await axios.get(
      `https://maps.googleapis.com/maps/api/place/details/json`,
      {
        params: {
          place_id: placeId,
          fields: "reviews,rating,user_ratings_total",
          key: apiKey,
          language: "en", // Optional: force English reviews
        },
      },
    );

    const data = googleResponse.data;

    if (data.status !== "OK") {
      // Handle cases where Place ID is invalid or API quota exceeded
      console.error("Google API Error:", data.status, data.error_message);
      // We return 200 with empty result so frontend falls back gracefully
      // instead of crashing the UI with a 500 error.
      return res.status(200).json({
        status: "success",
        result: { reviews: [] },
      });
    }

    res.status(200).json({
      status: "success",
      result: data.result,
    });
  } catch (error) {
    console.error("External API Request Failed:", error.message);
    return next(new AppError("Failed to fetch reviews from Google", 502));
  }
});
