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

async function linkStoreManagers() {
  try {
    // Connect to MongoDB
    await mongoose.connect(config.mongoose.url, config.mongoose.options);
    console.log('Connected to MongoDB');

    // Find all store managers without a store reference
    const storeManagers = await User.find({ 
      role: 'store_manager',
      $or: [
        { managedStore: { $exists: false } },
        { managedStore: null }
      ]
    });

    console.log(`Found ${storeManagers.length} store managers to process`);

    let updatedCount = 0;

    // Update each store manager with their store reference
    for (const manager of storeManagers) {
      // Find a store that references this manager
      const store = await Store.findOne({ storeManager: manager._id });
      
      if (store) {
        // Update the manager with the store reference
        manager.managedStore = store._id;
        await manager.save();
        updatedCount++;
        console.log(`Updated manager ${manager.email} with store ${store.store.storeName}`);
      } else {
        console.log(`No store found for manager ${manager.email}`);
      }
    }

    console.log(`\nMigration complete. Updated ${updatedCount} store managers.`);
    process.exit(0);
  } catch (error) {
    console.error('Migration error:', error);
    process.exit(1);
  }
}

// Run the migration
linkStoreManagers();
