const axios = require('axios');

const GOOGLE_MAPS_API_KEY = process.env.GOOGLE_MAPS_API_KEY;

const filterListingsByDistance = async (userLat, userLong, listings) => {
  if (!userLat || !userLong || listings.length === 0) return listings;

  const origins = `${userLat},${userLong}`;
  const destinations = listings.map((l) => `${l.latitude},${l.longitude}`).join('|');

  try {
    const url = `https://maps.googleapis.com/maps/api/distancematrix/json?origins=${origins}&destinations=${destinations}&key=${GOOGLE_MAPS_API_KEY}`;
    const response = await axios.get(url);

    const distances = response.data.rows[0].elements;

    // filter listings within 10km
    return listings.filter((listing, index) => {
      const distance = distances[index]?.distance?.value; // meters
      return distance !== undefined && distance <= 10000; // 10km limit
    });
  } catch (error) {
    console.error('Google Maps API Error:', error.message);
    return listings; // return original listings if API fails
  }
};

module.exports = { filterListingsByDistance };
