const mongoose = require('mongoose');
const uri = "mongodb+srv://admtracksteel:29OHAHpKTI8XcCNt@cluster0.a4xiilu.mongodb.net/ts_gpi?retryWrites=true&w=majority&appName=Cluster0";

async function migrateDB() {
    try {
        console.log('Connecting to MongoDB...');
        await mongoose.connect(uri);
        console.log('Connected.');

        const db = mongoose.connection.db;

        // 1. Rename clerkId to externalId in users
        console.log('Migrating Users...');
        await db.collection('users').updateMany(
            { clerkId: { $exists: true } },
            { $rename: { "clerkId": "externalId" } }
        );

        // 2. Rename clerkUserId to userId in organizationmembers
        console.log('Migrating OrganizationMembers...');
        await db.collection('organizationmembers').updateMany(
            { clerkUserId: { $exists: true } },
            { $rename: { "clerkUserId": "userId" } }
        );

        // 3. Rename clerkId to externalId in organizations
        console.log('Migrating Organizations...');
        await db.collection('organizations').updateMany(
            { clerkId: { $exists: true } },
            { $rename: { "clerkId": "externalId" } }
        );

        console.log('Migration completed successfully.');
        await mongoose.disconnect();
    } catch (err) {
        console.error('Migration failed:', err);
        process.exit(1);
    }
}

migrateDB();
