import mongoose from "mongoose";
import SettingProfile from "./models/settingProfile.js";

const connectDB = async () => {
  try {
    await mongoose.connect(
      "mongodb+srv://aliraza68629:X8qR2Dkp5jlXwPZk@cluster0.xsufbzs.mongodb.net/CSSAwwwards?retryWrites=true&w=majority&appName=Cluster0"
    );
    console.log(`✅ MongoDB Connected`);
  } catch (error) {
    console.error(`❌ Error: ${error.message}`);
    process.exit(1);
  }
};

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

  try {
    // Find all profiles
    const profiles = await SettingProfile.find({}).lean();
    
    console.log(`\n📊 Total profiles: ${profiles.length}\n`);
    
    // Find profiles with null username
    const nullUsernameProfiles = profiles.filter(p => p.username === null || p.username === undefined);
    
    console.log(`⚠️  Profiles with null username: ${nullUsernameProfiles.length}`);
    
    if (nullUsernameProfiles.length > 0) {
      console.log("\nProfiles with null username:");
      nullUsernameProfiles.forEach(profile => {
        console.log(`  ID: ${profile._id}, submittedBy: ${profile.submittedBy}`);
      });

      console.log("\n🗑️  Deleting profiles with null username...");
      const deleteResult = await SettingProfile.deleteMany({ 
        $or: [
          { username: null },
          { username: { $exists: false } }
        ]
      });
      console.log(`✅ Deleted ${deleteResult.deletedCount} profiles with null username`);
    }

    // Show remaining profiles
    const remaining = await SettingProfile.countDocuments();
    console.log(`\n📊 Remaining profiles: ${remaining}`);

    process.exit(0);
  } catch (error) {
    console.error("Error:", error);
    process.exit(1);
  }
};

cleanupProfiles();
