const mongoose = require('mongoose');
const config = require('../config/config');
const Store = require('../models/Store');

async function checkGeospatialIndex() {
  try {
    // Connect to MongoDB
    await mongoose.connect(config.mongoURI, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    });

    console.log('Connected to MongoDB');

    // Get the Store collection
    const collection = mongoose.connection.collection('stores');
    
    // Get all indexes
    const indexes = await collection.indexes();
    console.log('Current indexes:', JSON.stringify(indexes, null, 2));

    // Check if the geospatial index exists
    const geoIndex = indexes.find(index => 
      index.key && 
      index.key['store.location'] === '2dsphere'
    );

    if (geoIndex) {
      console.log('Geospatial index exists:', JSON.stringify(geoIndex, null, 2));
    } else {
      console.log('Geospatial index does not exist. Creating...');
      
      // Create the geospatial index
      await collection.createIndex(
        { 'store.location': '2dsphere' },
        { 
          name: 'store.location_2dsphere',
          background: true 
        }
      );
      
      console.log('Geospatial index created successfully');
    }

    // Check if there are any stores with valid coordinates
    const storesWithCoords = await Store.find({
      'store.location.coordinates.0': { $exists: true, $ne: 0 },
      'store.location.coordinates.1': { $exists: true, $ne: 0 }
    }).limit(5);

    console.log('Sample stores with coordinates:', 
      storesWithCoords.map(store => ({
        _id: store._id,
        name: store.name,
        location: store.store.location,
        deliveryRadius: store.store.deliveryRadius
      }))
    );

  } catch (error) {
    console.error('Error checking geospatial index:', error);
  } finally {
    // Close the connection
    await mongoose.connection.close();
    console.log('MongoDB connection closed');
  }
}

// Run the function
checkGeospatialIndex();
