/**
 * Password Migration Script
 * Updates existing users to have password fields
 */

const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const Player = require('../models/Player');
const logger = require('../utils/logger');
require('dotenv').config();

async function migratePasswords() {
    try {
        // Connect to database
        await mongoose.connect(process.env.MONGODB_URI);
        logger.info('Connected to database for password migration');

        // Find all users without passwords
        const usersWithoutPasswords = await Player.find({ 
            password: { $exists: false } 
        });

        logger.info(`Found ${usersWithoutPasswords.length} users without passwords`);

        if (usersWithoutPasswords.length === 0) {
            logger.info('No users need password migration');
            return;
        }

        // Update each user with a default password
        for (const user of usersWithoutPasswords) {
            // Generate a default password (you might want to use a different approach)
            const defaultPassword = 'tempPassword123!';
            const salt = await bcrypt.genSalt(10);
            const hashedPassword = await bcrypt.hash(defaultPassword, salt);

            await Player.updateOne(
                { _id: user._id },
                { 
                    $set: { 
                        password: hashedPassword,
                        'stats.lastLogin': new Date()
                    }
                }
            );

            logger.info(`Migrated user: ${user.email} with default password`);
        }

        logger.info('Password migration completed successfully');
        
        // Output the default password for users to change
        console.log('\n=== MIGRATION COMPLETE ===');
        console.log(`Updated ${usersWithoutPasswords.length} users`);
        console.log('Default password for all migrated users: tempPassword123!');
        console.log('Users should change their password after first login\n');

    } catch (error) {
        logger.error('Password migration error:', error);
        console.error('Migration failed:', error);
    } finally {
        await mongoose.disconnect();
    }
}

// Run the migration
if (require.main === module) {
    migratePasswords();
}

module.exports = migratePasswords;
