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

// Load env vars
dotenv.config({ path: path.resolve(__dirname, '../config/config.env') });

const connectDB = async () => {
  try {
    await mongoose.connect(process.env.MONGO_URI, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    console.log('MongoDB Connected...');
  } catch (err) {
    console.error(err.message);
    process.exit(1);
  }
};

const migrateStores = async () => {
  await connectDB();

  try {
    const stores = await Store.find();
    let usersCreated = 0;

    for (const store of stores) {
      // Check if a user already exists with this email
      const existingUser = await User.findOne({ email: store.email });

      if (!existingUser) {
        console.log(`Creating user for store: ${store.store.storeName} (${store.email})`);
        
        // Note: We don't have the original plain-text password.
        // We will set a temporary default password that the user should change later.
        const tempPassword = 'password123';

        await User.create({
          name: store.name,
          email: store.email,
          phone: store.mobile,
          password: tempPassword, // This will be hashed by the pre-save hook
          role: 'store_manager',
          status: store.status === 'Active',
        });
        usersCreated++;
      } else {
        console.log(`User already exists for email: ${store.email}. Skipping.`);
      }
    }

    console.log(`\nMigration complete. ${usersCreated} new user(s) created.`);
    console.log("IMPORTANT: Newly created users have a temporary password 'password123'. They should be advised to change it.");

  } catch (error) {
    console.error('Error during migration:', error);
  } finally {
    mongoose.connection.close();
  }
};

migrateStores();
