/**
 * Script to drop unique index on URL (profile URL) field
 * This allows the same profile URL to submit multiple websites
 * 
 * Usage: node drop-profile-url-index.js
 */

import mongoose from 'mongoose';
import dotenv from 'dotenv';

dotenv.config();

const MONGODB_URI = "mongodb+srv://aliraza68629:X8qR2Dkp5jlXwPZk@cluster0.xsufbzs.mongodb.net/CSSAwwwards?retryWrites=true&w=majority&appName=Cluster0";

async function dropProfileUrlIndex() {
    try {
        console.log('🔌 Connecting to MongoDB...');
        await mongoose.connect(MONGODB_URI);
        console.log('✅ Connected to MongoDB');

        const db = mongoose.connection.db;

        // Drop URL index from websitesubmissions collection
        console.log('\n📋 Processing websitesubmissions collection...');
        try {
            const websiteCollection = db.collection('websitesubmissions');

            // Drop URL (profile URL) unique index
            try {
                await websiteCollection.dropIndex('URL_1');
                console.log('✅ Dropped URL_1 index (profile URL)');
                console.log('ℹ️  Same profile URL can now be used for multiple website submissions');
            } catch (err) {
                if (err.code === 27) {
                    console.log('ℹ️  URL_1 index not found or already dropped');
                } else {
                    console.error('❌ Error dropping URL_1 index:', err.message);
                }
            }

            // List remaining indexes to confirm
            console.log('\n📋 Remaining indexes:');
            const indexes = await websiteCollection.indexes();
            indexes.forEach(index => {
                console.log(`   - ${JSON.stringify(index.key)}: ${index.name}`);
            });

        } catch (err) {
            console.log('⚠️  websitesubmissions collection not found');
        }

        console.log('\n✅ Migration completed!');
        console.log('ℹ️  Profile URLs can now be reused for multiple submissions.');
        console.log('ℹ️  Website URLs (Submitted_URL) remain unique.');

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

dropProfileUrlIndex();
