
import 'dotenv/config';
import mongoose from 'mongoose';

async function fixIndex() {
    try {
        const mongoUri = process.env.MONGODB_URI!;
        await mongoose.connect(mongoUri);
        console.log('Connected to MongoDB');

        const collection = mongoose.connection.collection('doctors');

        // List indexes first
        const indexes = await collection.indexes();
        console.log('Current indexes:', indexes);

        // Drop email_1 index if it exists
        const emailIndex = indexes.find(idx => idx.name === 'email_1');
        if (emailIndex) {
            console.log('Found email_1 index. Dropping...');
            await collection.dropIndex('email_1');
            console.log('✓ Dropped email_1 index');
        } else {
            console.log('email_1 index not found.');

            // Also check for licenseNumber index issues
            const licenseIndex = indexes.find(idx => idx.name === 'licenseNumber_1');
            if (licenseIndex) {
                console.log('Found licenseNumber_1 index. NOTE: If unique, multiple nulls will fail.');
                // We might want to make it sparse or drop it if it's causing issues, 
                // generally unique indexes on optional fields should be sparse.
                // Let's check if it is sparse.
                if (!licenseIndex.sparse) {
                    console.log('licenseNumber_1 is NOT sparse. Dropping and recreating as sparse...');
                    await collection.dropIndex('licenseNumber_1');
                    await collection.createIndex({ licenseNumber: 1 }, { unique: true, sparse: true });
                    console.log('✓ Recreated licenseNumber_1 as sparse');
                }
            }
        }

    } catch (error) {
        console.error('Error:', error);
    } finally {
        await mongoose.disconnect();
    }
}

fixIndex();
