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. ROOT - Full access to everything
    // ==========================================
    const rootPermissions = {};
    modules.forEach(module => {
      rootPermissions[module.name] = {};
      module.actions.forEach(action => {
        rootPermissions[module.name][action.name] = true;
      });
    });
    
    const rootRole = {
      name: 'root',
      displayName: 'Root',
      description: 'Full access across all child companies and modules',
      scope: 'global',
      isActive: true,
      modulePermissions: createRolePermissions(modules, rootPermissions)
    };
    
    // ==========================================
    // 2. SUPER ADMIN - Full access to everything
    // ==========================================
    const superAdminPermissions = {};
    modules.forEach(module => {
      superAdminPermissions[module.name] = {};
      module.actions.forEach(action => {
        superAdminPermissions[module.name][action.name] = true;
      });
    });
    
    const superAdminRole = {
      name: 'super_admin',
      displayName: 'Super Admin',
      description: 'Full access across all child companies and modules',
      scope: 'global',
      isActive: true,
      modulePermissions: createRolePermissions(modules, superAdminPermissions)
    };
    
    // ==========================================
    // 3. ADMIN - Company-level full access
    // ==========================================
    const adminPermissions = {};
    modules.forEach(module => {
      adminPermissions[module.name] = {};
      switch(module.name) {
        case 'libraries':
          module.actions.forEach(action => {
            if (['read', 'create', 'edit', 'delete', 'export', 'share'].includes(action.name)) {
              adminPermissions[module.name][action.name] = true;
            }
          });
          break;
      }
    });
    
    const adminRole = {
      name: 'admin',
      displayName: 'Admin',
      description: 'Full access within assigned company',
      scope: 'company',
      isActive: true,
      modulePermissions: createRolePermissions(modules, adminPermissions)
    };
    
    // ==========================================
    // 4. CHANNEL PARTNER - Limited access
    // ==========================================
    const channelPartnerPermissions = {};
    
    // Define specific permissions for channel partner
    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',
      scope: 'partner',
      isActive: true,
      modulePermissions: createRolePermissions(modules, channelPartnerPermissions)
    };
    
    // ==========================================
    // Clear existing roles and insert new ones
    // ==========================================
    console.log('🗑️  Clearing existing roles...\n');
    await Role.deleteMany({ name: { $in: ['root', 'super_admin', 'admin', 'channel_partner'] } });
    console.log('✅ Cleared existing roles\n');
    
    // Insert all roles
    console.log('📝 Creating roles...\n');
    const createdRoles = await Role.insertMany([
      rootRole,
      superAdminRole,
      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(`   🌍 Scope: ${role.scope}`);
      console.log(`   📦 Module Access: ${role.modulePermissions.length} modules`);
      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('');
      
      console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    });
    
    console.log('\n📝 SUMMARY:\n');
    console.log(`   ✓ Modules created: ${modules.length}`);
    console.log(`   ✓ Roles created: ${createdRoles.length}`);
    console.log(`     • Root (Scope: Global)`);
    console.log(`     • Super Admin (Scope: Global)`);
    console.log(`     • Admin (Scope: Company)`);
    console.log(`     • Channel Partner (Scope: 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();