const mongoose = require('mongoose');
const User = require('../models/User');
const Role = require('../models/Role');
const bcrypt = require('bcryptjs');
require('dotenv').config();

mongoose.connect(process.env.MONGODB_URI);

const seedUsers = async () => {
  try {
    console.log('\n🌱 Starting Users Creation Process...\n');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    
    // Fetch all roles
    console.log('🔍 Fetching roles from database...');
    const rootRole = await Role.findOne({ name: 'root' });
    const superAdminRole = await Role.findOne({ name: 'super_admin' });
    
    if (!rootRole || !superAdminRole) {
      console.log('\n❌ One or more roles not found!\n');
      console.log('💡 Please run the role seeder first:');
      console.log('   npm run seed:roles\n');
      console.log('Missing roles:');
      if (!rootRole) console.log('   - Root');
      if (!superAdminRole) console.log('   - Super Admin');
      console.log('');
      process.exit(1);
    }
    
    console.log('✅ All roles found\n');
    
    // Get password from environment or use default
    const defaultPassword = process.env.DEFAULT_USER_PASSWORD || 'Password@123';
    
    // Hash the password
    const hashedPassword = await bcrypt.hash(defaultPassword, 10);
    
    // Define sample users for each role
    const usersToCreate = [
      // Root User
      {
        email: 'root@arihant.com',
        password: hashedPassword,
        firstName: 'Root',
        lastName: 'User',
        phone: '+91-9000000001',
        roleId: rootRole._id,
        companies: [],
        status: 'active'
      },
      // Super Admin User
      {
        email: 'superadmin@arihant.com',
        password: hashedPassword,
        firstName: 'Super',
        lastName: 'Admin',
        phone: '+91-9000000002',
        roleId: superAdminRole._id,
        companies: [],
        status: 'active'
      }
    ];
    
    console.log('🔍 Checking for existing users...\n');
    
    // Check which users already exist
    const existingEmails = await User.find({
      email: { $in: usersToCreate.map(u => u.email) }
    }).select('email');
    
    const existingEmailSet = new Set(existingEmails.map(u => u.email));
    const newUsers = usersToCreate.filter(u => !existingEmailSet.has(u.email));
    
    if (existingEmailSet.size > 0) {
      console.log('⚠️  Found existing users:');
      existingEmailSet.forEach(email => {
        console.log(`   - ${email}`);
      });
      console.log('');
    }
    
    if (newUsers.length === 0) {
      console.log('✅ All sample users already exist!\n');
      console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
      
      // Display existing users
      const allUsers = await User.find({
        email: { $in: usersToCreate.map(u => u.email) }
      }).populate('roleId');
      
      console.log('📋 EXISTING USERS:\n');
      allUsers.forEach((user, index) => {
        console.log(`${index + 1}. ${user.firstName} ${user.lastName}`);
        console.log(`   📧 Email: ${user.email}`);
        console.log(`   📱 Phone: ${user.phone}`);
        console.log(`   🔐 Role: ${user.roleId.displayName}`);
        console.log(`   ✓ Status: ${user.status}`);
        console.log('');
      });
      
      console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
      console.log('💡 If you want to recreate users:');
      console.log('   1. Delete existing users from database');
      console.log('   2. Or modify emails in this seeder script\n');
      process.exit(0);
    }
    
    // Create new users
    console.log(`👤 Creating ${newUsers.length} new user(s)...\n`);
    const createdUsers = await User.insertMany(newUsers);
    
    console.log(`✅ ${createdUsers.length} user(s) created successfully!\n`);
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    
    // Display created users details
    console.log('📋 CREATED USERS DETAILS:\n');
    
    const createdUsersWithRoles = await User.find({
      _id: { $in: createdUsers.map(u => u._id) }
    }).populate('roleId');
    
    createdUsersWithRoles.forEach((user, index) => {
      console.log(`${index + 1}. ${user.firstName} ${user.lastName}`);
      console.log(`   📧 Email: ${user.email}`);
      console.log(`   📱 Phone: ${user.phone}`);
      console.log(`   🔐 Role: ${user.roleId.displayName}`);
      console.log(`   🌍 Scope: ${user.roleId.scope}`);
      console.log(`   ✓ Status: ${user.status}`);
      console.log(`   📅 Created: ${user.createdAt.toLocaleString()}`);
      console.log('');
    });
    
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    console.log('🔑 LOGIN CREDENTIALS:\n');
    console.log(`   🔒 Default Password for all users: ${defaultPassword}\n`);
    
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    console.log('📊 SUMMARY BY ROLE:\n');
    console.log(`   👑 Root: 1 user`);
    console.log(`   🔐 Super Admin: 1 user`);
    console.log(`   ━━━━━━━━━━━━━━━━━━━━━`);
    console.log(`   📝 Total: ${createdUsers.length} users created\n`);
    
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    console.log('⚠️  SECURITY WARNING:\n');
    console.log('   🔴 These are SAMPLE users for development/testing');
    console.log('   🔴 Change all passwords after first login!');
    console.log('   🔴 Never use these credentials in production!');
    console.log('   🔴 Delete or disable sample users in production!\n');
    
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    console.log('🎉 User seeding completed successfully!\n');
    console.log('💡 NEXT STEPS:\n');
    console.log('   1. Start the server: npm run dev');
    console.log('   2. Login at: POST /api/v1/auth/login');
    console.log('   3. Use any email from above');
    console.log(`   4. Use password: ${defaultPassword}`);
    console.log('   5. Test different role permissions\n');
    
    process.exit(0);
    
  } catch (error) {
    console.error('\n❌ Error creating users:', error);
    console.error('\nError details:', error.message);
    
    if (error.code === 11000) {
      console.error('\n💡 Duplicate key error - User with this email/phone already exists');
      console.error('   Duplicate field:', Object.keys(error.keyPattern)[0]);
      console.error('   Value:', Object.values(error.keyValue)[0]);
    }
    
    if (error.name === 'ValidationError') {
      console.error('\n💡 Validation errors:');
      Object.keys(error.errors).forEach(key => {
        console.error(`   - ${key}: ${error.errors[key].message}`);
      });
    }
    
    console.error('\nStack trace:', error.stack);
    process.exit(1);
  }
};

seedUsers();