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

const systemModules = [
  // ============================================
  // ADMIN MODULES
  // ============================================
  {
    name: 'companies',
    displayName: 'Company Management',
    description: 'Manage child companies and their settings',
    icon: 'building',
    category: 'admin',
    route: '/companies',
    order: 1,
    isActive: true,
    actions: [
      { name: 'read', displayName: 'View/Read', description: 'View companies and their details' },
      { name: 'create', displayName: 'Create', description: 'Create new companies' },
      { name: 'edit', displayName: 'Edit/Update', description: 'Edit company details and settings' },
      { name: 'delete', displayName: 'Delete', description: 'Delete companies' },
      { name: 'export', displayName: 'Export', description: 'Export company data' }
    ]
  },
  {
    name: 'users',
    displayName: 'User Management',
    description: 'Manage users, roles, and access permissions',
    icon: 'users',
    category: 'admin',
    route: '/users',
    order: 2,
    isActive: true,
    actions: [
      { name: 'read', displayName: 'View/Read', description: 'View users and their profiles' },
      { name: 'create', displayName: 'Create', description: 'Create new users' },
      { name: 'edit', displayName: 'Edit/Update', description: 'Edit user details and permissions' },
      { name: 'delete', displayName: 'Delete', description: 'Delete users' },
      { name: 'export', displayName: 'Export', description: 'Export user data' }
    ]
  },
  {
    name: 'roles',
    displayName: 'Role Management',
    description: 'Manage roles and permissions',
    icon: 'shield',
    category: 'admin',
    route: '/roles',
    order: 3,
    isActive: true,
    actions: [
      { name: 'read', displayName: 'View/Read', description: 'View roles and permissions' },
      { name: 'create', displayName: 'Create', description: 'Create new roles' },
      { name: 'edit', displayName: 'Edit/Update', description: 'Edit role permissions' },
      { name: 'delete', displayName: 'Delete', description: 'Delete custom roles' }
    ]
  },

  // ============================================
  // CRM MODULES
  // ============================================
  {
    name: 'products',
    displayName: 'Product Management',
    description: 'Manage products, pricing, and inventory',
    icon: 'package',
    category: 'crm',
    route: '/products',
    order: 4,
    isActive: true,
    actions: [
      { name: 'read', displayName: 'View/Read', description: 'View products and details' },
      { name: 'create', displayName: 'Create', description: 'Create new products' },
      { name: 'edit', displayName: 'Edit/Update', description: 'Edit product details and pricing' },
      { name: 'delete', displayName: 'Delete', description: 'Delete products' },
      { name: 'export', displayName: 'Export', description: 'Export product catalog' },
      { name: 'import', displayName: 'Import', description: 'Import products in bulk' }
    ]
  },
  {
    name: 'leads',
    displayName: 'Lead Management',
    description: 'Manage customer leads, prospects, and opportunities',
    icon: 'target',
    category: 'crm',
    route: '/leads',
    order: 5,
    isActive: true,
    actions: [
      { name: 'read', displayName: 'View/Read', description: 'View leads and their status' },
      { name: 'create', displayName: 'Create', description: 'Create new leads' },
      { name: 'edit', displayName: 'Edit/Update', description: 'Edit lead details and status' },
      { name: 'delete', displayName: 'Delete', description: 'Delete leads' },
      { name: 'export', displayName: 'Export', description: 'Export leads data' },
      { name: 'import', displayName: 'Import', description: 'Import leads in bulk' },
      { name: 'assign', displayName: 'Assign', description: 'Assign leads to team members' }
    ]
  },
  {
    name: 'proposals',
    displayName: 'Proposal Management',
    description: 'Create, manage, and track proposals',
    icon: 'file-text',
    category: 'crm',
    route: '/proposals',
    order: 6,
    isActive: true,
    actions: [
      { name: 'read', displayName: 'View/Read', description: 'View proposals and their status' },
      { name: 'create', displayName: 'Create', description: 'Create new proposals' },
      { name: 'edit', displayName: 'Edit/Update', description: 'Edit proposal details' },
      { name: 'delete', displayName: 'Delete', description: 'Delete proposals' },
      { name: 'export', displayName: 'Download', description: 'Download proposals as PDF' },
      { name: 'approve', displayName: 'Approve', description: 'Approve proposals' },
      { name: 'reject', displayName: 'Reject', description: 'Reject proposals' }
    ]
  },
  {
    name: 'quotations',
    displayName: 'Quotation Management',
    description: 'Manage quotations and pricing',
    icon: 'dollar-sign',
    category: 'crm',
    route: '/quotations',
    order: 7,
    isActive: true,
    actions: [
      { name: 'read', displayName: 'View/Read', description: 'View quotations' },
      { name: 'create', displayName: 'Create', description: 'Create new quotations' },
      { name: 'edit', displayName: 'Edit/Update', description: 'Edit quotation details' },
      { name: 'delete', displayName: 'Delete', description: 'Delete quotations' },
      { name: 'export', displayName: 'Download', description: 'Download quotations as PDF' },
      { name: 'approve', displayName: 'Approve', description: 'Approve quotations' }
    ]
  },

  // ============================================
  // DOCUMENT & LIBRARY MODULES
  // ============================================
  {
    name: 'libraries',
    displayName: 'Library Management',
    description: 'Manage document library and shared resources',
    icon: 'book',
    category: 'crm',
    route: '/libraries',
    order: 8,
    isActive: true,
    actions: [
      { name: 'read', displayName: 'View/Read', description: 'View library documents' },
      { name: 'create', displayName: 'Create', description: 'Upload new documents' },
      { name: 'edit', displayName: 'Edit/Update', description: 'Edit document details' },
      { name: 'delete', displayName: 'Delete', description: 'Delete documents' },
      { name: 'export', displayName: 'Download', description: 'Download documents' },
      { name: 'share', displayName: 'Share', description: 'Share documents with team/clients' }
    ]
  },

  // ============================================
  // SLA & SUPPORT MODULES
  // ============================================
  {
    name: 'sla',
    displayName: 'SLA Management',
    description: 'Manage Service Level Agreements and compliance',
    icon: 'clock',
    category: 'crm',
    route: '/sla',
    order: 9,
    isActive: true,
    actions: [
      { name: 'read', displayName: 'View/Read', description: 'View SLA details and status' },
      { name: 'create', displayName: 'Create', description: 'Create new SLA agreements' },
      { name: 'edit', displayName: 'Edit/Update', description: 'Edit SLA terms and conditions' },
      { name: 'delete', displayName: 'Delete', description: 'Delete SLA agreements' },
      { name: 'export', displayName: 'Export', description: 'Export SLA reports' }
    ]
  },
  {
    name: 'support',
    displayName: 'Support & Tickets',
    description: 'Manage customer support tickets and queries',
    icon: 'headphones',
    category: 'crm',
    route: '/support',
    order: 10,
    isActive: true,
    actions: [
      { name: 'read', displayName: 'View/Read', description: 'View support tickets' },
      { name: 'create', displayName: 'Create', description: 'Create new support tickets' },
      { name: 'edit', displayName: 'Edit/Update', description: 'Update ticket status and details' },
      { name: 'delete', displayName: 'Delete', description: 'Delete tickets' },
      { name: 'assign', displayName: 'Assign', description: 'Assign tickets to team members' },
      { name: 'resolve', displayName: 'Resolve', description: 'Mark tickets as resolved' },
      { name: 'export', displayName: 'Export', description: 'Export ticket data' }
    ]
  },

  // ============================================
  // REPORTS & ANALYTICS MODULES
  // ============================================
  {
    name: 'reports',
    displayName: 'Reports',
    description: 'View and generate business reports',
    icon: 'bar-chart',
    category: 'reports',
    route: '/reports',
    order: 11,
    isActive: true,
    actions: [
      { name: 'read', displayName: 'View/Read', description: 'View reports and dashboards' },
      { name: 'create', displayName: 'Generate', description: 'Generate custom reports' },
      { name: 'export', displayName: 'Export', description: 'Export reports (PDF/Excel)' },
      { name: 'schedule', displayName: 'Schedule', description: 'Schedule automated reports' }
    ]
  },
  {
    name: 'analytics',
    displayName: 'Analytics',
    description: 'View analytics, insights, and KPIs',
    icon: 'trending-up',
    category: 'analytics',
    route: '/analytics',
    order: 12,
    isActive: true,
    actions: [
      { name: 'read', displayName: 'View/Read', description: 'View analytics and insights' },
      { name: 'export', displayName: 'Export', description: 'Export analytics data' }
    ]
  },

  // ============================================
  // SETTINGS MODULE
  // ============================================
  {
    name: 'settings',
    displayName: 'Settings',
    description: 'System and company settings configuration',
    icon: 'settings',
    category: 'settings',
    route: '/settings',
    order: 13,
    isActive: true,
    actions: [
      { name: 'read', displayName: 'View/Read', description: 'View system settings' },
      { name: 'edit', displayName: 'Edit/Update', description: 'Update system settings' }
    ]
  },

  // ============================================
  // ACTIVITY LOGS MODULE
  // ============================================
  {
    name: 'activity_logs',
    displayName: 'Activity Logs',
    description: 'View system activity and audit logs',
    icon: 'activity',
    category: 'admin',
    route: '/activity-logs',
    order: 14,
    isActive: true,
    actions: [
      { name: 'read', displayName: 'View/Read', description: 'View activity logs' },
      { name: 'export', displayName: 'Export', description: 'Export activity logs' }
    ]
  }
];

const seedModules = async () => {
  try {
    console.log('\n🌱 Starting Module Seeding Process...\n');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    
    // Clear existing modules
    const deleteCount = await Module.countDocuments();
    await Module.deleteMany({});
    console.log(`✅ Cleared ${deleteCount} existing modules\n`);
    
    // Insert all modules
    const createdModules = await Module.insertMany(systemModules);
    console.log(`✅ Successfully created ${createdModules.length} modules\n`);
    
    // Group modules by category for better display
    const modulesByCategory = createdModules.reduce((acc, module) => {
      if (!acc[module.category]) {
        acc[module.category] = [];
      }
      acc[module.category].push(module);
      return acc;
    }, {});
    
    // Display created modules grouped by category
    console.log('📦 MODULES CREATED:\n');
    
    const categoryNames = {
      admin: '👤 ADMIN MODULES',
      crm: '💼 CRM MODULES',
      workflow: '🔄 WORKFLOW MODULES',
      reports: '📊 REPORTS MODULES',
      analytics: '📈 ANALYTICS MODULES',
      settings: '⚙️  SETTINGS MODULES'
    };
    
    Object.keys(modulesByCategory).forEach(category => {
      console.log(`${categoryNames[category] || category.toUpperCase()}`);
      console.log('─'.repeat(45));
      modulesByCategory[category].forEach(module => {
        console.log(`   ${module.icon.padEnd(15)} ${module.displayName}`);
        console.log(`   ${''.padEnd(15)} └─ ${module.actions.length} actions available`);
      });
      console.log('');
    });
    
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    console.log('📋 SUMMARY:\n');
    console.log(`   ✓ Total Modules: ${createdModules.length}`);
    console.log(`   ✓ Admin Modules: ${modulesByCategory.admin?.length || 0}`);
    console.log(`   ✓ CRM Modules: ${modulesByCategory.crm?.length || 0}`);
    console.log(`   ✓ Workflow Modules: ${modulesByCategory.workflow?.length || 0}`);
    console.log(`   ✓ Report Modules: ${modulesByCategory.reports?.length || 0}`);
    console.log(`   ✓ Analytics Modules: ${modulesByCategory.analytics?.length || 0}`);
    console.log(`   ✓ Settings Modules: ${modulesByCategory.settings?.length || 0}\n`);
    
    const totalActions = createdModules.reduce((sum, module) => sum + module.actions.length, 0);
    console.log(`   ✓ Total Actions: ${totalActions}\n`);
    
    console.log('✅ Module seeding completed successfully!\n');
    
    // Return created modules for role seeding
    return createdModules;
    
  } catch (error) {
    console.error('\n❌ Error seeding modules:', error);
    console.error('\nStack trace:', error.stack);
    throw error;
  }
};

// Run directly or export for use in other seed scripts
if (require.main === module) {
  mongoose.connect(process.env.MONGODB_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  })
  .then(() => {
    console.log('✅ Connected to MongoDB');
    return seedModules();
  })
  .then(() => {
    console.log('🎉 All done!');
    process.exit(0);
  })
  .catch((error) => {
    console.error('❌ Fatal error:', error);
    process.exit(1);
  });
}

module.exports = seedModules;