// Fix missing submittedBy fields in database
import mongoose from 'mongoose';
import dotenv from 'dotenv';
import WebsiteSubmission from './models/websiteSubmission.js';
import SubmitDirectory from './models/submitDirectory.js';
import SubmitAiWebsite from './models/submitAiWebsite.js';

dotenv.config();

async function fixMissingSubmittedBy() {
  try {
    console.log('🔌 Connecting to MongoDB...');
    await mongoose.connect(process.env.MONGO_URI);
    console.log('✅ Connected\n');

    // Check nominee websites
    console.log('📊 Checking WebsiteSubmission (Nominee) collection...');
    const nomineesWithoutUser = await WebsiteSubmission.find({ 
      $or: [
        { submittedBy: { $exists: false } },
        { submittedBy: null }
      ]
    });
    console.log(`Found ${nomineesWithoutUser.length} nominees without submittedBy`);
    
    if (nomineesWithoutUser.length > 0) {
      nomineesWithoutUser.forEach(item => {
        console.log(`  - ID: ${item._id}, Title: ${item.Title}`);
      });
      console.log('\n⚠️  These records need a user assigned to them.');
      console.log('   Option 1: Delete them (if they\'re test data)');
      console.log('   Option 2: Assign them to a default user\n');
    }

    // Check directories
    console.log('📊 Checking SubmitDirectory collection...');
    const directoriesWithoutUser = await SubmitDirectory.find({ 
      $or: [
        { submittedBy: { $exists: false } },
        { submittedBy: null }
      ]
    });
    console.log(`Found ${directoriesWithoutUser.length} directories without submittedBy`);
    
    if (directoriesWithoutUser.length > 0) {
      directoriesWithoutUser.forEach(item => {
        console.log(`  - ID: ${item._id}, Title: ${item.Title}`);
      });
    }

    // Check AI websites
    console.log('\n📊 Checking SubmitAiWebsite collection...');
    const aiWebsitesWithoutUser = await SubmitAiWebsite.find({ 
      $or: [
        { submittedBy: { $exists: false } },
        { submittedBy: null }
      ]
    });
    console.log(`Found ${aiWebsitesWithoutUser.length} AI websites without submittedBy`);
    
    if (aiWebsitesWithoutUser.length > 0) {
      aiWebsitesWithoutUser.forEach(item => {
        console.log(`  - ID: ${item._id}, Title: ${item.title}`);
      });
    }

    const totalInvalid = nomineesWithoutUser.length + directoriesWithoutUser.length + aiWebsitesWithoutUser.length;

    if (totalInvalid > 0) {
      console.log('\n❓ What would you like to do?');
      console.log('   1. Delete these records');
      console.log('   2. Keep them (they\'ll show as "Anonymous" in the UI)');
      console.log('\n💡 The UI has been updated to handle missing submittedBy gracefully.');
      console.log('   Records will display "Anonymous" and "?" as initials.');
    } else {
      console.log('\n✅ All records have valid submittedBy fields!');
    }

    // Check if submittedBy references exist
    console.log('\n🔍 Checking if submittedBy references are valid...');
    
    const nomineesWithInvalidRef = await WebsiteSubmission.find({ 
      submittedBy: { $ne: null } 
    }).populate('submittedBy');
    
    const invalidNominees = nomineesWithInvalidRef.filter(item => !item.submittedBy);
    
    if (invalidNominees.length > 0) {
      console.log(`⚠️  Found ${invalidNominees.length} nominees with invalid user references (user was deleted)`);
      invalidNominees.forEach(item => {
        console.log(`  - ID: ${item._id}, Title: ${item.Title}`);
      });
    } else {
      console.log('✅ All submittedBy references are valid!');
    }

  } catch (error) {
    console.error('❌ Error:', error);
  } finally {
    await mongoose.connection.close();
    console.log('\n🔌 Disconnected');
  }
}

fixMissingSubmittedBy();
