/**
 * User Seeder
 * Creates default users for the system (admin, manager, cashier)
 */

// Import bcrypt for password hashing
const bcrypt = require('bcryptjs');

/**
 * Seed users into database
 * @param {Object} db - Database models object
 */
const seedUsers = async (db) => {
  // Import User model from database
  const { User } = db;
  
  // Default users to create
  const defaultUsers = [
    {
      username: 'admin', // System administrator username
      email: 'admin@xyzpos.com', // Admin email
      password: 'admin123', // Password (will be hashed)
      full_name: 'System Administrator', // Full name
      role: 'system_admin', // Role: system admin
      pin_code: '1234', // PIN code for quick login (will be hashed)
      active: true, // User is active
    },
    {
      username: 'manager', // Manager username
      email: 'manager@xyzpos.com', // Manager email
      password: 'manager123', // Password (will be hashed)
      full_name: 'Store Manager', // Full name
      role: 'manager', // Role: manager
      pin_code: '5678', // PIN code for quick login (will be hashed)
      active: true, // User is active
    },
    {
      username: 'cashier', // Cashier username
      email: 'cashier@xyzpos.com', // Cashier email
      password: 'cashier123', // Password (will be hashed)
      full_name: 'POS Cashier', // Full name
      role: 'cashier', // Role: cashier
      pin_code: '9999', // PIN code for quick login (will be hashed)
      active: true, // User is active
    },
  ];
  
  // Check if users already exist
  const existingUsers = await User.findAll({
    where: {
      username: defaultUsers.map(u => u.username), // Find users with these usernames
    },
  });
  
  // If users already exist, skip seeding
  if (existingUsers.length > 0) {
    console.log('⚠️  Users already exist. Skipping user seeding.');
    return; // Exit function
  }
  
  // Create users (passwords and PINs will be hashed by model hooks)
  for (const userData of defaultUsers) {
    // Create user (password hashing happens in model hook)
    await User.create(userData);
    console.log(`✅ Created user: ${userData.username} (${userData.role})`);
  }
  
  console.log('✅ User seeding completed!');
};

// Export seed function
module.exports = seedUsers;

