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

mongoose.connect(process.env.MONGODB_URI);

const seedCompanies = async () => {
  try {
    console.log('\n🌱 Starting Company Creation Process...\n');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    
    // Check if root user exists
    console.log('🔍 Checking for root user (Birendra Yadav)...');
    const rootUser = await User.findOne({ email: 'root@arihant.com' });
    
    if (!rootUser) {
      console.log('\n❌ Root user not found!\n');
      console.log('💡 Please run the super admin seeder first:');
      console.log('   npm run seed:admin\n');
      process.exit(1);
    }
    
    console.log('✅ Root user found\n');
    console.log(`   👤 Name: ${rootUser.firstName} ${rootUser.lastName}`);
    console.log(`   📧 Email: ${rootUser.email}`);
    console.log(`   🆔 ID: ${rootUser._id}\n`);
    
    // Define companies to seed
    const companiesToSeed = [
      {
        name: 'Arihant Water Slides',
        code: 'IF',
        parentCompany: 'Arihant Industries',
        status: 'active',
        contact: {
          email: 'info@arihantwaterslides.com',
          phone: '+91-9876543210',
          address: {
            street: '123, Industrial Area, Sector 5',
            city: 'Noida',
            state: 'Uttar Pradesh',
            pincode: '201301',
            country: 'India'
          }
        },
        settings: {
          allowAdditionalAdmin: true,
          workflowEnabled: true,
          requireVerifier: true
        },
        createdBy: rootUser._id
      },
      {
        name: 'Arihant Play',
        code: 'PT',
        parentCompany: 'Arihant Industries',
        status: 'active',
        contact: {
          email: 'info@arihantplay.com',
          phone: '+91-9876543211',
          address: {
            street: '456, Recreation Zone, Phase 2',
            city: 'Gurgaon',
            state: 'Haryana',
            pincode: '122001',
            country: 'India'
          }
        },
        settings: {
          allowAdditionalAdmin: true,
          workflowEnabled: true,
          requireVerifier: true
        },
        createdBy: rootUser._id
      },
      {
        name: 'The Great Escape Water Park',
        code: 'TGE',
        parentCompany: 'Arihant Industries',
        status: 'active',
        contact: {
          email: 'info@thegreatescape.com',
          phone: '+91-9876543212',
          address: {
            street: '789, Entertainment District',
            city: 'Mumbai',
            state: 'Maharashtra',
            pincode: '400001',
            country: 'India'
          }
        },
        settings: {
          allowAdditionalAdmin: true,
          workflowEnabled: true,
          requireVerifier: true
        },
        createdBy: rootUser._id
      }
    ];
    
    // Check for existing companies
    console.log('🔍 Checking for existing companies...\n');
    const existingCompanies = await Company.find({
      code: { $in: companiesToSeed.map(c => c.code) }
    });
    
    if (existingCompanies.length > 0) {
      console.log('⚠️  Found existing companies:\n');
      
      existingCompanies.forEach((company, index) => {
        console.log(`   ${index + 1}. ${company.name} (${company.code})`);
        console.log(`      📧 Email: ${company.contact.email}`);
        console.log(`      📍 Location: ${company.contact.address.city}, ${company.contact.address.state}`);
        console.log(`      ✓ Status: ${company.status}`);
        console.log(`      📅 Created: ${company.createdAt.toLocaleString()}\n`);
      });
      
      console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
      console.log('💡 OPTIONS:\n');
      console.log('   1. Delete existing companies from database');
      console.log('   2. Or use the --force flag to recreate them:');
      console.log('      npm run seed:companies -- --force\n');
      
      if (!process.argv.includes('--force')) {
        process.exit(0);
      }
      
      console.log('🗑️  --force flag detected. Deleting existing companies...\n');
      await Company.deleteMany({
        code: { $in: companiesToSeed.map(c => c.code) }
      });
      console.log('✅ Existing companies deleted\n');
    } else {
      console.log('✅ No existing companies found\n');
    }
    
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    console.log('🏢 Creating Companies...\n');
    
    const createdCompanies = [];
    let successCount = 0;
    let failCount = 0;
    
    // Create companies one by one
    for (let i = 0; i < companiesToSeed.length; i++) {
      const companyData = companiesToSeed[i];
      
      try {
        console.log(`📍 [${i + 1}/${companiesToSeed.length}] Creating ${companyData.name}...`);
        
        const company = await Company.create(companyData);
        createdCompanies.push(company);
        successCount++;
        
        console.log(`   ✅ Created successfully`);
        console.log(`      🆔 ID: ${company._id}`);
        console.log(`      📧 Email: ${company.contact.email}`);
        console.log(`      📍 Location: ${company.contact.address.city}, ${company.contact.address.state}\n`);
        
      } catch (error) {
        failCount++;
        console.log(`   ❌ Failed to create ${companyData.name}`);
        console.log(`      Error: ${error.message}\n`);
      }
    }
    
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    console.log('📊 SEEDING SUMMARY:\n');
    console.log(`   ✅ Successfully created: ${successCount}/${companiesToSeed.length}`);
    console.log(`   ❌ Failed: ${failCount}/${companiesToSeed.length}\n`);
    
    if (createdCompanies.length > 0) {
      console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
      console.log('📋 CREATED COMPANIES DETAILS:\n');
      
      createdCompanies.forEach((company, index) => {
        console.log(`${index + 1}. ${company.name}`);
        console.log('   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        console.log(`   🆔 Company ID: ${company._id}`);
        console.log(`   🏷️  Company Code: ${company.code}`);
        console.log(`   🏢 Parent Company: ${company.parentCompany}`);
        console.log(`   ✓  Status: ${company.status}`);
        console.log('');
        console.log('   📞 CONTACT INFORMATION:');
        console.log(`      📧 Email: ${company.contact.email}`);
        console.log(`      📱 Phone: ${company.contact.phone}`);
        console.log('');
        console.log('   📍 ADDRESS:');
        console.log(`      ${company.contact.address.street}`);
        console.log(`      ${company.contact.address.city}, ${company.contact.address.state} - ${company.contact.address.pincode}`);
        console.log(`      ${company.contact.address.country}`);
        console.log('');
        console.log('   ⚙️  SETTINGS:');
        console.log(`      ${company.settings.allowAdditionalAdmin ? '✓' : '✗'} Allow Additional Admin`);
        console.log(`      ${company.settings.workflowEnabled ? '✓' : '✗'} Workflow Enabled`);
        console.log(`      ${company.settings.requireVerifier ? '✓' : '✗'} Require Verifier`);
        console.log('');
        console.log(`   👤 Created By: ${rootUser.firstName} ${rootUser.lastName} (${rootUser.email})`);
        console.log(`   📅 Created At: ${company.createdAt.toLocaleString()}`);
        console.log('');
      });
      
      console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
      console.log('📦 COMPANY IDS (for reference):\n');
      
      createdCompanies.forEach(company => {
        console.log(`   ${company.code.padEnd(10)} : ${company._id}`);
      });
      console.log('');
    }
    
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    console.log('🎉 Company seeding completed successfully!\n');
    console.log('💡 NEXT STEPS:\n');
    console.log('   1. Companies are now available in the system');
    console.log('   2. You can create company admins for these companies');
    console.log('   3. Assign users to specific companies');
    console.log('   4. Configure company-specific settings\n');
    
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    console.log('📚 USEFUL COMMANDS:\n');
    console.log('   • View all companies:');
    console.log('     GET /api/v1/companies\n');
    console.log('   • View specific company:');
    console.log('     GET /api/v1/companies/:companyId\n');
    console.log('   • Update company:');
    console.log('     PUT /api/v1/companies/:companyId\n');
    
    process.exit(0);
    
  } catch (error) {
    console.error('\n❌ Error creating companies:', error);
    console.error('\nError details:', error.message);
    
    if (error.code === 11000) {
      console.error('\n💡 Duplicate key error - Company with this code already exists');
      console.error('   Check the "code" field for duplicates');
    }
    
    if (error.name === 'ValidationError') {
      console.error('\n💡 Validation errors:');
      Object.keys(error.errors).forEach(key => {
        console.error(`   - ${key}: ${error.errors[key].message}`);
      });
    }
    
    if (error.name === 'CastError') {
      console.error('\n💡 Invalid ID format - Check the createdBy field');
    }
    
    console.error('\n📋 Stack trace:');
    console.error(error.stack);
    console.error('');
    
    process.exit(1);
  }
};

seedCompanies();