
import * as dotenv from 'dotenv';
import mongoose from 'mongoose';
import path from 'path';

// Load environment variables
dotenv.config({ path: path.join(__dirname, '../../.env') });

const MONGODB_URI = process.env.MONGODB_URI || "mongodb://localhost:27017/clinic-management";

async function fixIndexes() {
    try {
        console.log('Connecting to MongoDB...', MONGODB_URI);
        await mongoose.connect(MONGODB_URI);
        console.log('Connected to MongoDB.');

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

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

        // Look for index on email
        const emailIndex = indexes.find((idx: any) => idx.key.email === 1 || idx.name === 'email_1');

        if (emailIndex && emailIndex.name) {
            console.log(`Found stray index: ${emailIndex.name}. Dropping...`);
            await collection.dropIndex(emailIndex.name);
            console.log('Index dropped successfully.');
        } else {
            console.log('No stray email index found.');
        }

    } catch (error) {
        console.error('Error executing script:', error);
    } finally {
        await mongoose.disconnect();
        console.log('Disconnected.');
        process.exit(0);
    }
}

fixIndexes();
