import dotenv from 'dotenv';
import mongoose from 'mongoose';
import path from 'path';
import User from '../models/User';

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

async function normalizeEmails() {
  try {
    const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/clinic-management';
    await mongoose.connect(mongoUri);
    console.log('✓ Connected to MongoDB');

    // Find all users
    const users = await User.find({});
    console.log(`Found ${users.length} users to process`);

    let updatedCount = 0;
    let skippedCount = 0;

    for (const user of users) {
      const normalizedEmail = user.email.toLowerCase();
      
      if (user.email !== normalizedEmail) {
        // Check if normalized email already exists
        const existingUser = await User.findOne({ email: normalizedEmail });
        if (existingUser && existingUser._id.toString() !== user._id.toString()) {
          console.log(`⚠️  Skipping ${user.email} - lowercase version already exists`);
          skippedCount++;
          continue;
        }

        // Update email to lowercase
        user.email = normalizedEmail;
        await user.save();
        console.log(`✓ Updated ${user.email}`);
        updatedCount++;
      }
    }

    console.log(`\n✓ Migration complete!`);
    console.log(`  - Updated: ${updatedCount} users`);
    console.log(`  - Skipped: ${skippedCount} users`);

    mongoose.connection.close();
  } catch (error: any) {
    console.error('Error during normalization:', error.message);
    process.exit(1);
  }
}

normalizeEmails();
