// Quick test to verify favorites are working
import mongoose from 'mongoose';
import dotenv from 'dotenv';
import Favorite from './models/favorite.js';

dotenv.config();

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

    // Test 1: Check all favorites
    const all = await Favorite.find();
    console.log(`📊 Total favorites: ${all.length}`);
    all.forEach((fav, i) => {
      console.log(`${i + 1}. User ID: ${fav.user}, Type: ${fav.itemType}`);
    });

    // Test 2: Try to create a duplicate (should fail)
    console.log('\n🧪 Testing duplicate prevention...');
    const existingFav = all[0];
    if (existingFav) {
      const duplicateData = {
        user: existingFav.user._id,
        itemType: existingFav.itemType,
      };
      
      if (existingFav.itemType === 'nominee') {
        duplicateData.nomineeWebsite = existingFav.nomineeWebsite;
      } else if (existingFav.itemType === 'directory') {
        duplicateData.directory = existingFav.directory;
      } else if (existingFav.itemType === 'ai') {
        duplicateData.aiWebsite = existingFav.aiWebsite;
      }

      try {
        await Favorite.create(duplicateData);
        console.log('❌ ERROR: Duplicate was allowed!');
      } catch (error) {
        if (error.code === 11000) {
          console.log('✅ Duplicate prevention working! (E11000 error as expected)');
        } else {
          console.log('⚠️  Different error:', error.message);
        }
      }
    }

    // Test 3: Check indexes
    console.log('\n📋 Indexes:');
    const indexes = await Favorite.collection.getIndexes();
    Object.keys(indexes).forEach(name => {
      console.log(`  - ${name}`);
    });

    console.log('\n✅ All tests passed!');
    
  } catch (error) {
    console.error('❌ Test failed:', error);
  } finally {
    await mongoose.connection.close();
    console.log('\n🔌 Disconnected');
  }
}

test();
