const express = require('express');
const { auth } = require('../middleware/auth');
const {
  detectLocation,
  getUserLocation,
  updateUserLocation,
  deleteUserLocation,
  reverseGeocode,
  getNearbyStores,
  geocode,
  getCurrentLocation
} = require('../controllers/locationController');

const router = express.Router();

// Public routes
// @desc    Reverse geocode coordinates to address
// @access  Public
router.get("/reverse", async (req, res) => {
  try {
    const { lat, lon } = req.query;
    
    if (!lat || !lon) {
      return res.status(400).json({ 
        success: false,
        error: "Latitude and longitude are required" 
      });
    }

    // Call Nominatim API (OpenStreetMap)
    const response = await axios.get("https://nominatim.openstreetmap.org/reverse", {
      params: {
        lat,
        lon,
        format: "json",
        addressdetails: 1,
        "accept-language": "en"
      },
      headers: {
        'User-Agent': 'Helthstra-App/1.0' // Required by Nominatim
      }
    });

    const { address } = response.data;
    
    // Extract relevant address components
    const locationData = {
      displayName: response.data.display_name,
      address: {
        city: address.city || address.town || address.village || address.hamlet || address.county || '',
        state: address.state || address.region || '',
        country: address.country || '',
        postcode: address.postcode || '',
        road: address.road || '',
        houseNumber: address.house_number || ''
      },
      coordinates: [parseFloat(lon), parseFloat(lat)] // [longitude, latitude] for GeoJSON
    };

    res.json({
      success: true,
      data: locationData
    });
  } catch (error) {
    console.error('Reverse geocoding error:', error);
    res.status(500).json({
      success: false,
      error: "Failed to retrieve location information"
    });
  }
});

// Protected routes (require authentication)
router
  .route('/')
  .get(auth, getUserLocation)
  .put(auth, updateUserLocation)
  .delete(auth, deleteUserLocation);

// Public routes
router.get('/geocode', geocode);
router.get('/nearby-stores', getNearbyStores);

// Protected routes (require authentication)
router.use(auth);
router.get('/current', getCurrentLocation);
router.route('/')
  .get(getUserLocation)
  .put(updateUserLocation)
  .delete(deleteUserLocation);

// Admin routes
router.get('/detect', auth, detectLocation);
router.get('/reverse', reverseGeocode);

module.exports = router;
