import mongoose from 'mongoose';
import bcrypt from 'bcryptjs';
import { v4 as uuidv4 } from 'uuid';

const MONGODB_URI = 'mongodb+srv://admtracksteel:29OHAHpKTI8XcCNt@cluster0.a4xiilu.mongodb.net/ts_gpi?retryWrites=true&w=majority&appName=Cluster0';

const UserSchema = new mongoose.Schema({
    externalId: { type: String, required: true, unique: true },
    email: { type: String, required: true, unique: true },
    passwordHash: { type: String, required: true },
    name: { type: String, required: true },
    role: { type: String, enum: ['guest', 'user', 'admin'], default: 'guest' },
    organizationId: String,
    isBanned: { type: Boolean, default: false }
}, { timestamps: true });

async function fixAdmin() {
    try {
        await mongoose.connect(MONGODB_URI);
        console.log('✅ Conectado ao MongoDB');

        const User = mongoose.models.User || mongoose.model('User', UserSchema);

        const email = 'admtracksteel@gmail.com';
        const password = 'admin'; // Senha padrão temporária
        const hashedPassword = await bcrypt.hash(password, 10);

        // Tenta encontrar o usuário existente
        let user = await User.findOne({ email });

        if (user) {
            const result = await User.updateOne(
                { email },
                { 
                    $set: { 
                        role: 'admin',
                        passwordHash: hashedPassword,
                        name: 'Admin TrackSteel'
                    } 
                }
            );
            console.log(`✅ Usuário ${email} atualizado para admin e senha definida.`);
        } else {
            const fakeAuthId = `user_${uuidv4().replace(/-/g, '')}`;
            await User.create({
                externalId: fakeAuthId,
                email,
                passwordHash: hashedPassword,
                name: 'Admin TrackSteel',
                role: 'admin',
                organizationId: 'default-org'
            });
            console.log(`✅ Usuário ${email} criado como admin (AuthId: ${fakeAuthId}).`);
        }

        // Listar todos os usuários
        const users = await User.find({});
        console.log('\n📋 Usuários atuais:');
        users.forEach((u, i) => {
            console.log(`  ${i + 1}. ${u.email} | role: ${u.role} | hasHash: ${!!u.passwordHash}`);
        });

    } catch (err) {
        console.error('❌ Erro durante a execução:', err);
    } finally {
        await mongoose.disconnect();
        console.log('\n✅ Desconectado do MongoDB');
        process.exit(0);
    }
}

fixAdmin();
