import dotenv from 'dotenv';
import mongoose from 'mongoose';
import { User } from './models/user.js';

// Load environment variables
dotenv.config();

/**
 * Migration Script: Mark Existing Users as Verified
 * 
 * This script sets isVerified = true for all existing users
 * who don't have the isVerified field yet.
 * 
 * Run this ONCE after deploying the verification system
 * to ensure existing users can still login.
 */

const migrateExistingUsers = async () => {
  try {
    console.log('🔄 Starting migration: Marking existing users as verified...\n');

    // Connect to MongoDB
    await mongoose.connect(process.env.MONGO_URI);
    console.log('✅ Connected to MongoDB\n');

    // Find users without isVerified field or where it's null/undefined
    const unverifiedUsers = await User.find({
      $or: [
        { isVerified: { $exists: false } },
        { isVerified: null }
      ]
    });

    console.log(`📊 Found ${unverifiedUsers.length} existing users without verification status\n`);

    if (unverifiedUsers.length === 0) {
      console.log('✅ No users to migrate. All users already have verification status.');
      await mongoose.connection.close();
      return;
    }

    // Update all existing users to verified
    const result = await User.updateMany(
      {
        $or: [
          { isVerified: { $exists: false } },
          { isVerified: null }
        ]
      },
      {
        $set: { isVerified: true }
      }
    );

    console.log('✅ Migration completed successfully!');
    console.log(`   - Users updated: ${result.modifiedCount}`);
    console.log(`   - Users matched: ${result.matchedCount}\n`);

    // Verify the migration
    const stillUnverified = await User.countDocuments({
      $or: [
        { isVerified: { $exists: false } },
        { isVerified: null },
        { isVerified: false }
      ]
    });

    if (stillUnverified > 0) {
      console.log(`⚠️  Warning: ${stillUnverified} users still without verification status`);
    } else {
      console.log('✅ Verification: All users now have verified status');
    }

    console.log('\n📋 Summary:');
    const totalUsers = await User.countDocuments();
    const verifiedUsers = await User.countDocuments({ isVerified: true });
    const unverifiedNewUsers = await User.countDocuments({ isVerified: false });

    console.log(`   Total users: ${totalUsers}`);
    console.log(`   Verified users: ${verifiedUsers}`);
    console.log(`   Unverified users (need email verification): ${unverifiedNewUsers}`);

    await mongoose.connection.close();
    console.log('\n✅ Database connection closed');
    console.log('\n🎉 Migration complete! Existing users can now login without email verification.');

  } catch (error) {
    console.error('❌ Migration failed:', error);
    process.exit(1);
  }
};

// Run migration
migrateExistingUsers();
