const mongoose = require('mongoose');
const Role = require('../models/Role');
const Module = require('../models/Module');
const seedModules = require('./seedModules');
require('dotenv').config();

// Connect to MongoDB
mongoose.connect(process.env.MONGODB_URI);

// Helper function to create role permissions
const createRolePermissions = (modules, permissionConfig) => {
  return modules.map(module => {
    const permissions = permissionConfig[module.name] || {};
    return {
      moduleId: module._id,
      moduleName: module.name,
      permissions: permissions
    };
  }).filter(mp => Object.keys(mp.permissions).length > 0);
};

const seedRoles = async () => {
  try {
    console.log('\n🌱 Starting Role Seeding Process...\n');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    
    // First, seed modules
    console.log('📦 Step 1: Seeding Modules\n');
    const modules = await seedModules();
    
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    console.log('👥 Step 2: Seeding Roles\n');
    
    // ==========================================
    // 1. GLOBAL ADMIN - Full access to everything
    // ==========================================
    const globalAdminPermissions = {};
    modules.forEach(module => {
      globalAdminPermissions[module.name] = {};
      module.actions.forEach(action => {
        globalAdminPermissions[module.name][action.name] = true;
      });
    });
    
    const globalAdminRole = {
      name: 'global_admin',
      displayName: 'Global Admin',
      description: 'Full access across all child companies and modules',
      level: 0,
      scope: 'global',
      isSystemRole: true,
      isActive: true,
      modulePermissions: createRolePermissions(modules, globalAdminPermissions),
      specialPermissions: [
        'access_all_companies',
        'manage_roles',
        'view_audit_logs',
        'system_configuration',
        'manage_modules',
        'impersonate_users'
      ]
    };
    
    // ==========================================
    // 2. ADMIN - Company-level full access
    // ==========================================
    const adminPermissions = {};
    modules.forEach(module => {
      adminPermissions[module.name] = {};
      module.actions.forEach(action => {
        // Admin gets all permissions except system-level ones
        if (!action.name.includes('system') && !action.name.includes('global')) {
          adminPermissions[module.name][action.name] = true;
        }
      });
    });
    
    const adminRole = {
      name: 'admin',
      displayName: 'Admin',
      description: 'Full access within assigned company',
      level: 1,
      scope: 'company',
      isSystemRole: true,
      isActive: true,
      modulePermissions: createRolePermissions(modules, adminPermissions),
      specialPermissions: [
        'manage_users',
        'manage_company_settings',
        'view_reports',
        'manage_departments',
        'view_audit_logs'
      ]
    };
    
    // ==========================================
    // 3. CHANNEL PARTNER - Limited access
    // ==========================================
    const channelPartnerPermissions = {};
    
    // Define specific permissions for channel partner
    // Adjust these based on your actual module names
    modules.forEach(module => {
      channelPartnerPermissions[module.name] = {};
      
      switch(module.name) {
        case 'libraries':
          module.actions.forEach(action => {
            if (['read', 'export', 'share'].includes(action.name)) {
              channelPartnerPermissions[module.name][action.name] = true;
            }
          });
          break;
      }
    });
    
    const channelPartnerRole = {
      name: 'channel_partner',
      displayName: 'Channel Partner',
      description: 'Limited access for external partners to manage leads and opportunities',
      level: 2,
      scope: 'partner',
      isSystemRole: true,
      isActive: true,
      modulePermissions: createRolePermissions(modules, channelPartnerPermissions),
      specialPermissions: [
        'view_assigned_leads',
        'create_opportunities',
        'view_own_reports'
      ]
    };
    
    // ==========================================
    // Clear existing roles and insert new ones
    // ==========================================
    console.log('🗑️  Clearing existing system roles...\n');
    await Role.deleteMany({ isSystemRole: true });
    console.log('✅ Cleared existing system roles\n');
    
    // Insert all roles
    console.log('📝 Creating roles...\n');
    const createdRoles = await Role.insertMany([
      globalAdminRole,
      adminRole,
      channelPartnerRole
    ]);
    
    console.log('✅ All roles created successfully!\n');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    
    // Display details for each role
    createdRoles.forEach((role, index) => {
      console.log(`\n📋 ROLE ${index + 1} DETAILS:\n`);
      console.log(`   🔐 Role Name: ${role.displayName} (${role.name})`);
      console.log(`   📊 Level: ${role.level}`);
      console.log(`   🌍 Scope: ${role.scope}`);
      console.log(`   📦 Module Access: ${role.modulePermissions.length} modules`);
      console.log(`   🔑 Special Permissions: ${role.specialPermissions.length}`);
      console.log('');
      
      // Display module permissions
      console.log('   📦 MODULE PERMISSIONS:');
      role.modulePermissions.forEach(mp => {
        const module = modules.find(m => m._id.equals(mp.moduleId));
        const permissionCount = Object.keys(Object.fromEntries(mp.permissions)).filter(k => mp.permissions.get(k)).length;
        console.log(`      ✓ ${module.displayName.padEnd(25)} - ${permissionCount}/${module.actions.length} actions`);
      });
      console.log('');
      
      // Display special permissions
      console.log('   🔑 SPECIAL PERMISSIONS:');
      role.specialPermissions.forEach(permission => {
        console.log(`      ✓ ${permission}`);
      });
      
      console.log('\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    });
    
    console.log('\n📝 SUMMARY:\n');
    console.log(`   ✓ Modules created: ${modules.length}`);
    console.log(`   ✓ Roles created: ${createdRoles.length}`);
    console.log(`     • Global Admin (Level 0 - Global)`);
    console.log(`     • Admin (Level 1 - Company)`);
    console.log(`     • Channel Partner (Level 2 - Partner)`);
    console.log('');
    
    console.log('💡 NOTE: Additional custom roles can be created via API endpoints\n');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    console.log('✅ Database setup completed successfully!\n');
    console.log('🎉 You can now create users with these roles!\n');
    
    process.exit(0);
    
  } catch (error) {
    console.error('\n❌ Error seeding roles:', error);
    console.error('\nStack trace:', error.stack);
    process.exit(1);
  }
};

// Run the seed function
seedRoles();