const { sequelize } = require('./config/db');
const { User, Role } = require('./models/foundation');
const bcrypt = require('bcryptjs');

const seed = async () => {
    try {
        await sequelize.sync({ force: false });

        const [adminRole] = await Role.findOrCreate({ where: { constant: 'SUPER_ADMIN' }, defaults: { name: 'Super Admin' } });

        const password = await bcrypt.hash('password123', 10);

        const [user, created] = await User.findOrCreate({
            where: { email: 'lawreyk@gmail.com' },
            defaults: {
                fullName: 'Lawrey K',
                password,
                roleId: adminRole.id,
                isActive: true
            }
        });

        if (!created) {
            // ensure correct password if user existed
            user.password = password;
            await user.save();
            console.log('Updated existing user');
        }

        console.log('✅ Created/Updated lawreyk@gmail.com');
        process.exit(0);
    } catch (err) {
        console.error('❌ Seeding failed:', err);
        process.exit(1);
    }
};

seed();
