const { PushToken } = require('../models');

const locationUpdates = [];

exports.update = async (req, res) => {
  try {
    const { email, latitude, longitude, country, timestamp } = req.body;
    if (!email || latitude == null || longitude == null) {
      return res.status(400).json({ error: 'Email, latitude, and longitude are required' });
    }

    const record = { email, latitude, longitude, country: country || null, timestamp: timestamp || new Date().toISOString() };
    locationUpdates.push(record);

    if (locationUpdates.length > 1000) {
      locationUpdates.splice(0, locationUpdates.length - 1000);
    }

    res.json({ message: 'Location updated' });
  } catch (error) {
    console.error('[Location] Update error:', error.message);
    res.status(500).json({ error: 'Failed to update location' });
  }
};

exports.getByEmail = async (req, res) => {
  try {
    const { email } = req.params;
    const userLocations = locationUpdates.filter((l) => l.email === email);
    const latest = userLocations[userLocations.length - 1] || null;
    res.json({ locations: userLocations.slice(-50), latest });
  } catch (error) {
    res.status(500).json({ error: 'Failed to get locations' });
  }
};

exports.nearby = async (req, res) => {
  try {
    const { latitude, longitude, radiusKm = 100 } = req.query;
    if (!latitude || !longitude) {
      return res.status(400).json({ error: 'Latitude and longitude required' });
    }

    const lat = parseFloat(latitude);
    const lng = parseFloat(longitude);
    const radius = parseFloat(radiusKm);

    const latestByEmail = new Map();
    for (const loc of locationUpdates) {
      latestByEmail.set(loc.email, loc);
    }

    const nearby = [];
    for (const loc of latestByEmail.values()) {
      const dist = haversineDistance(lat, lng, loc.latitude, loc.longitude);
      if (dist <= radius) {
        nearby.push({ ...loc, distanceKm: Math.round(dist * 10) / 10 });
      }
    }

    res.json({ nearby: nearby.sort((a, b) => a.distanceKm - b.distanceKm) });
  } catch (error) {
    res.status(500).json({ error: 'Failed to find nearby' });
  }
};

function haversineDistance(lat1, lon1, lat2, lon2) {
  const R = 6371;
  const dLat = toRad(lat2 - lat1);
  const dLon = toRad(lon2 - lon1);
  const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
    Math.sin(dLon / 2) * Math.sin(dLon / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  return R * c;
}

function toRad(deg) {
  return deg * (Math.PI / 180);
}
