// seeders/productSeeder.js
const mongoose = require('mongoose');
const Product = require('../models/Product');
const Company = require('../models/Company');
const User = require('../models/User');
require('dotenv').config();

mongoose.connect(process.env.MONGODB_URI);

const seedProducts = async () => {
  try {
    console.log('\n🌱 Starting Product Creation Process...\n');
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    
    // Check if root user exists
    console.log('🔍 Checking for root user...');
    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');
    console.log(`   👤 ${rootUser.firstName} ${rootUser.lastName}\n`);
    
    // Fetch all companies
    console.log('🔍 Fetching companies...');
    const companies = await Company.find({ status: 'active' });
    
    if (companies.length === 0) {
      console.log('\n❌ No companies found!\n');
      console.log('💡 Please run the company seeder first:');
      console.log('   npm run seed:companies\n');
      process.exit(1);
    }
    
    console.log(`✅ Found ${companies.length} companies:\n`);
    companies.forEach((company, index) => {
      console.log(`   ${index + 1}. ${company.name} (${company.code}) - ID: ${company._id}`);
    });
    console.log('');
    
    // Define products for each company
    const productsData = {
      // Arihant Water Slides (IF) - Water slide products
      'IF': [
        {
          name: 'Tornado Water Slide - Large',
          description: 'High-speed tornado funnel water slide with 360-degree spiral. Perfect for thrill-seekers. Capacity: 4 riders per raft.',
          category: 'Water Slides',
          subCategory: 'Tornado Slides',
          brand: 'Arihant Premium',
          sku: 'IF-TOR-L-001',
          barcode: '8901234567890',
          pricing: {
            cost: 850000,
            price: 1200000,
            salePrice: 1100000,
            currency: 'INR',
            taxRate: 18
          },
          inventory: {
            trackInventory: true,
            quantity: 15,
            minStockLevel: 3,
            maxStockLevel: 50,
            unit: 'piece'
          },
          dimensions: {
            weight: 5500,
            length: 2400,
            width: 1800,
            height: 1200,
            unit: 'cm'
          },
          specifications: {
            'Material': 'Fiberglass Reinforced Plastic (FRP)',
            'Height': '12 meters',
            'Capacity': '4 riders per raft',
            'Age Group': '10+ years',
            'Safety Features': 'Anti-slip surface, safety rails',
            'Installation Time': '5-7 days',
            'Warranty': '3 years'
          },
          tags: ['water slide', 'tornado', 'thrill ride', 'water park', 'family attraction'],
          status: 'active',
          isPublished: true,
          isFeatured: true,
          supplier: {
            name: 'FRP Solutions India',
            contact: '+91-9876543220',
            email: 'sales@frpsolutions.com'
          },
          warranty: {
            duration: 3,
            unit: 'years',
            terms: 'Covers manufacturing defects and structural issues. Excludes wear and tear.'
          },
          metadata: {
            views: 245,
            sales: 8,
            rating: 4.7,
            reviews: 12
          }
        },
        {
          name: 'Family Raft Slide - Multi-lane',
          description: 'Multi-lane family raft slide with gentle slopes. Suitable for all age groups. 4 parallel lanes for racing fun.',
          category: 'Water Slides',
          subCategory: 'Raft Slides',
          brand: 'Arihant Family',
          sku: 'IF-FRS-M-002',
          barcode: '8901234567891',
          pricing: {
            cost: 650000,
            price: 950000,
            currency: 'INR',
            taxRate: 18
          },
          inventory: {
            trackInventory: true,
            quantity: 22,
            minStockLevel: 5,
            maxStockLevel: 60,
            unit: 'piece'
          },
          dimensions: {
            weight: 4200,
            length: 1800,
            width: 1500,
            height: 900,
            unit: 'cm'
          },
          specifications: {
            'Material': 'UV-resistant FRP',
            'Height': '8 meters',
            'Lanes': '4 lanes',
            'Capacity': '2-3 riders per raft',
            'Age Group': 'All ages',
            'Safety Features': 'Soft landing pool, safety nets',
            'Installation Time': '3-4 days'
          },
          tags: ['water slide', 'family', 'multi-lane', 'raft slide', 'racing'],
          status: 'active',
          isPublished: true,
          isFeatured: true,
          supplier: {
            name: 'FRP Solutions India',
            contact: '+91-9876543220',
            email: 'sales@frpsolutions.com'
          },
          warranty: {
            duration: 2,
            unit: 'years',
            terms: 'Manufacturer warranty on structural components'
          },
          metadata: {
            views: 312,
            sales: 15,
            rating: 4.8,
            reviews: 18
          }
        },
        {
          name: 'Speed Racer Body Slide',
          description: 'High-speed body slide with steep drops and twists. Adrenaline-pumping experience for thrill lovers.',
          category: 'Water Slides',
          subCategory: 'Body Slides',
          brand: 'Arihant Extreme',
          sku: 'IF-SPD-B-003',
          barcode: '8901234567892',
          pricing: {
            cost: 450000,
            price: 680000,
            currency: 'INR',
            taxRate: 18
          },
          inventory: {
            trackInventory: true,
            quantity: 30,
            minStockLevel: 8,
            maxStockLevel: 80,
            unit: 'piece'
          },
          dimensions: {
            weight: 2800,
            length: 1500,
            width: 800,
            height: 600,
            unit: 'cm'
          },
          specifications: {
            'Material': 'Premium FRP',
            'Height': '10 meters',
            'Type': 'Body slide',
            'Age Group': '12+ years',
            'Speed': 'High speed',
            'Safety Features': 'Water jets, soft landing',
            'Colors Available': 'Red, Blue, Yellow, Green'
          },
          tags: ['water slide', 'body slide', 'speed', 'thrill', 'extreme'],
          status: 'active',
          isPublished: true,
          isFeatured: false,
          supplier: {
            name: 'AquaTech Industries',
            contact: '+91-9876543221',
            email: 'info@aquatech.in'
          },
          warranty: {
            duration: 18,
            unit: 'months',
            terms: 'Limited warranty on manufacturing defects'
          },
          metadata: {
            views: 198,
            sales: 12,
            rating: 4.5,
            reviews: 9
          }
        },
        {
          name: 'Wave Pool System - Commercial',
          description: 'Advanced wave pool system with programmable wave patterns. Create ocean-like waves for ultimate fun.',
          category: 'Wave Systems',
          subCategory: 'Wave Pools',
          brand: 'Arihant WaveTech',
          sku: 'IF-WPS-C-004',
          barcode: '8901234567893',
          pricing: {
            cost: 2500000,
            price: 3800000,
            salePrice: 3500000,
            currency: 'INR',
            taxRate: 18
          },
          inventory: {
            trackInventory: true,
            quantity: 5,
            minStockLevel: 2,
            maxStockLevel: 15,
            unit: 'piece'
          },
          dimensions: {
            weight: 8500,
            length: 3000,
            width: 2500,
            height: 1800,
            unit: 'cm'
          },
          specifications: {
            'Wave Height': 'Up to 2.5 meters',
            'Pool Size': 'Custom (25m x 40m recommended)',
            'Wave Patterns': '8 programmable patterns',
            'Power': '150 HP motor',
            'Control System': 'Digital touchscreen',
            'Capacity': '500+ swimmers',
            'Installation Time': '15-20 days'
          },
          tags: ['wave pool', 'wave system', 'commercial', 'water park', 'attraction'],
          status: 'active',
          isPublished: true,
          isFeatured: true,
          supplier: {
            name: 'WaveMaster Technologies',
            contact: '+91-9876543222',
            email: 'sales@wavemaster.com'
          },
          warranty: {
            duration: 5,
            unit: 'years',
            terms: 'Comprehensive warranty on motor and mechanical parts'
          },
          metadata: {
            views: 425,
            sales: 3,
            rating: 4.9,
            reviews: 6
          }
        },
        {
          name: 'Lazy River Float System',
          description: 'Complete lazy river system with current generators and themed elements. Relaxing water ride experience.',
          category: 'River Systems',
          subCategory: 'Lazy River',
          brand: 'Arihant Flow',
          sku: 'IF-LRS-F-005',
          barcode: '8901234567894',
          pricing: {
            cost: 1800000,
            price: 2800000,
            currency: 'INR',
            taxRate: 18
          },
          inventory: {
            trackInventory: true,
            quantity: 8,
            minStockLevel: 2,
            maxStockLevel: 20,
            unit: 'piece'
          },
          dimensions: {
            weight: 6200,
            length: 3500,
            width: 2000,
            height: 1500,
            unit: 'cm'
          },
          specifications: {
            'Current Speed': 'Adjustable 0.5-2 km/h',
            'River Length': 'Custom (200m recommended)',
            'Depth': '1.2 meters',
            'Flow Rate': '5000 liters/minute',
            'Features': 'Waterfalls, sprays, themed elements',
            'Capacity': '200+ floats',
            'Installation Time': '12-15 days'
          },
          tags: ['lazy river', 'river system', 'relaxation', 'water park', 'family'],
          status: 'active',
          isPublished: true,
          isFeatured: false,
          supplier: {
            name: 'AquaFlow Systems',
            contact: '+91-9876543223',
            email: 'contact@aquaflow.in'
          },
          warranty: {
            duration: 3,
            unit: 'years',
            terms: 'Warranty on pumps and filtration system'
          },
          metadata: {
            views: 287,
            sales: 5,
            rating: 4.6,
            reviews: 8
          }
        }
      ],
      
      // Arihant Play (PT) - Playground equipment
      'PT': [
        {
          name: 'Multi-Play Station - Deluxe',
          description: 'Complete outdoor play station with slides, swings, climbing walls, and activity panels. Heavy-duty construction.',
          category: 'Playground Equipment',
          subCategory: 'Multi-Play Stations',
          brand: 'Arihant Play Pro',
          sku: 'PT-MPS-D-001',
          barcode: '8902234567890',
          pricing: {
            cost: 180000,
            price: 285000,
            salePrice: 265000,
            currency: 'INR',
            taxRate: 18
          },
          inventory: {
            trackInventory: true,
            quantity: 35,
            minStockLevel: 10,
            maxStockLevel: 100,
            unit: 'piece'
          },
          dimensions: {
            weight: 850,
            length: 800,
            width: 600,
            height: 400,
            unit: 'cm'
          },
          specifications: {
            'Material': 'Powder-coated steel, HDPE',
            'Age Group': '3-12 years',
            'Capacity': '15-20 children',
            'Components': 'Slides (2), Swings (4), Climbing wall, Activity panels',
            'Safety': 'Rounded edges, anti-slip steps',
            'UV Resistant': 'Yes',
            'Weather Proof': 'Yes',
            'Installation': 'Professional installation included'
          },
          tags: ['playground', 'multi-play', 'outdoor', 'children', 'school', 'park'],
          status: 'active',
          isPublished: true,
          isFeatured: true,
          supplier: {
            name: 'PlayEquip India',
            contact: '+91-9876543230',
            email: 'sales@playequip.in'
          },
          warranty: {
            duration: 2,
            unit: 'years',
            terms: 'Warranty on structural components and hardware'
          },
          metadata: {
            views: 568,
            sales: 24,
            rating: 4.7,
            reviews: 32
          }
        },
        {
          name: 'Kids Swing Set - 4 Seater',
          description: 'Heavy-duty swing set with 4 seats. Features adjustable chains and comfortable seats. Perfect for parks and schools.',
          category: 'Playground Equipment',
          subCategory: 'Swings',
          brand: 'Arihant Swing',
          sku: 'PT-SWG-4-002',
          barcode: '8902234567891',
          pricing: {
            cost: 35000,
            price: 58000,
            currency: 'INR',
            taxRate: 18
          },
          inventory: {
            trackInventory: true,
            quantity: 65,
            minStockLevel: 15,
            maxStockLevel: 150,
            unit: 'piece'
          },
          dimensions: {
            weight: 180,
            length: 400,
            width: 250,
            height: 280,
            unit: 'cm'
          },
          specifications: {
            'Material': 'Heavy gauge steel, UV-resistant seats',
            'Seats': '4 swing seats',
            'Age Group': '3-12 years',
            'Load Capacity': '50 kg per seat',
            'Chain': 'Galvanized, adjustable',
            'Colors': 'Red, Blue, Yellow, Green seats',
            'Ground Fixing': 'Concrete embedding required'
          },
          tags: ['swing', 'playground', 'outdoor', 'children', 'school', 'garden'],
          status: 'active',
          isPublished: true,
          isFeatured: false,
          supplier: {
            name: 'PlayEquip India',
            contact: '+91-9876543230',
            email: 'sales@playequip.in'
          },
          warranty: {
            duration: 18,
            unit: 'months',
            terms: 'Warranty against manufacturing defects'
          },
          metadata: {
            views: 423,
            sales: 38,
            rating: 4.6,
            reviews: 28
          }
        },
        {
          name: 'Outdoor Seesaw - Double',
          description: 'Classic seesaw with spring action and comfortable handles. Safe design with shock absorbers.',
          category: 'Playground Equipment',
          subCategory: 'Seesaws',
          brand: 'Arihant Classic',
          sku: 'PT-SSW-D-003',
          barcode: '8902234567892',
          pricing: {
            cost: 18000,
            price: 32000,
            currency: 'INR',
            taxRate: 18
          },
          inventory: {
            trackInventory: true,
            quantity: 48,
            minStockLevel: 12,
            maxStockLevel: 120,
            unit: 'piece'
          },
          dimensions: {
            weight: 85,
            length: 280,
            width: 60,
            height: 90,
            unit: 'cm'
          },
          specifications: {
            'Material': 'Powder-coated steel, HDPE seat',
            'Capacity': '2 children',
            'Age Group': '3-10 years',
            'Load Capacity': '40 kg per side',
            'Safety': 'Shock absorbers, rubber handles',
            'Spring Action': 'Yes',
            'Colors': 'Multi-color options'
          },
          tags: ['seesaw', 'playground', 'outdoor', 'children', 'classic', 'fun'],
          status: 'active',
          isPublished: true,
          isFeatured: false,
          supplier: {
            name: 'KidsPlay Manufacturing',
            contact: '+91-9876543231',
            email: 'info@kidsplay.in'
          },
          warranty: {
            duration: 12,
            unit: 'months',
            terms: 'Limited warranty on structural parts'
          },
          metadata: {
            views: 312,
            sales: 42,
            rating: 4.5,
            reviews: 24
          }
        },
        {
          name: 'Climbing Frame Tower - Adventure',
          description: 'Multi-level climbing tower with rope nets, rock climbing wall, and observation deck. Adventure playground equipment.',
          category: 'Playground Equipment',
          subCategory: 'Climbing Structures',
          brand: 'Arihant Adventure',
          sku: 'PT-CLM-A-004',
          barcode: '8902234567893',
          pricing: {
            cost: 125000,
            price: 195000,
            currency: 'INR',
            taxRate: 18
          },
          inventory: {
            trackInventory: true,
            quantity: 18,
            minStockLevel: 5,
            maxStockLevel: 50,
            unit: 'piece'
          },
          dimensions: {
            weight: 520,
            length: 500,
            width: 500,
            height: 450,
            unit: 'cm'
          },
          specifications: {
            'Material': 'Heavy-duty steel frame, rope nets',
            'Age Group': '5-12 years',
            'Height': '4.5 meters',
            'Capacity': '10-12 children',
            'Features': 'Climbing wall, rope net, lookout tower',
            'Safety': 'Non-slip surfaces, safety railings',
            'Installation': 'Professional installation required'
          },
          tags: ['climbing', 'adventure', 'playground', 'outdoor', 'tower', 'active'],
          status: 'active',
          isPublished: true,
          isFeatured: true,
          supplier: {
            name: 'Adventure Play Systems',
            contact: '+91-9876543232',
            email: 'sales@adventureplay.in'
          },
          warranty: {
            duration: 2,
            unit: 'years',
            terms: 'Comprehensive warranty on frame and components'
          },
          metadata: {
            views: 445,
            sales: 14,
            rating: 4.8,
            reviews: 19
          }
        },
        {
          name: 'Sandbox Play Area - Large',
          description: 'Large capacity sandbox with weather cover and seating bench. Perfect for creative play and sensory development.',
          category: 'Playground Equipment',
          subCategory: 'Sand Play',
          brand: 'Arihant Creative',
          sku: 'PT-SBX-L-005',
          barcode: '8902234567894',
          pricing: {
            cost: 28000,
            price: 48000,
            currency: 'INR',
            taxRate: 18
          },
          inventory: {
            trackInventory: true,
            quantity: 32,
            minStockLevel: 8,
            maxStockLevel: 80,
            unit: 'piece'
          },
          dimensions: {
            weight: 145,
            length: 300,
            width: 300,
            height: 40,
            unit: 'cm'
          },
          specifications: {
            'Material': 'Treated wood, UV-resistant cover',
            'Size': '3m x 3m',
            'Capacity': '8-10 children',
            'Age Group': '2-8 years',
            'Features': 'Weather cover, corner seats, drainage holes',
            'Sand Capacity': '1 cubic meter',
            'Treatment': 'Weather-resistant coating'
          },
          tags: ['sandbox', 'sand play', 'playground', 'creative', 'sensory', 'outdoor'],
          status: 'active',
          isPublished: true,
          isFeatured: false,
          supplier: {
            name: 'Outdoor Play Solutions',
            contact: '+91-9876543233',
            email: 'contact@outdoorplay.in'
          },
          warranty: {
            duration: 18,
            unit: 'months',
            terms: 'Warranty on wood treatment and structure'
          },
          metadata: {
            views: 289,
            sales: 26,
            rating: 4.4,
            reviews: 15
          }
        }
      ]
    };
    
    // Check for existing products
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    console.log('🔍 Checking for existing products...\n');
    
    const existingProductsCount = await Product.countDocuments();
    
    if (existingProductsCount > 0) {
      console.log(`⚠️  Found ${existingProductsCount} existing products in database\n`);
      console.log('💡 OPTIONS:\n');
      console.log('   1. Delete existing products from database');
      console.log('   2. Or use the --force flag to recreate them:');
      console.log('      npm run seed:products -- --force\n');
      
      if (!process.argv.includes('--force')) {
        process.exit(0);
      }
      
      console.log('🗑️  --force flag detected. Deleting existing products...\n');
      await Product.deleteMany({});
      console.log('✅ Existing products deleted\n');
    } else {
      console.log('✅ No existing products found\n');
    }
    
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    console.log('📦 Creating Products...\n');
    
    const createdProducts = [];
    let totalSuccess = 0;
    let totalFail = 0;
    
    // Create products for each company
    for (const company of companies) {
      const companyProducts = productsData[company.code];
      
      if (!companyProducts || companyProducts.length === 0) {
        console.log(`⚠️  No products defined for ${company.name}\n`);
        continue;
      }
      
      console.log(`\n🏢 ${company.name} (${company.code})`);
      console.log(`   Creating ${companyProducts.length} products...\n`);
      
      let companySuccess = 0;
      let companyFail = 0;
      
      // Get current product count for this company to generate proper codes
      const existingCount = await Product.countDocuments({ companyId: company._id });
      
      for (let i = 0; i < companyProducts.length; i++) {
        // Generate productCode manually
        const productCode = `PRD-${company.code}-${String(existingCount + i + 1).padStart(5, '0')}`;
        
        const productData = {
          ...companyProducts[i],
          productCode, // Add the generated productCode
          companyId: company._id,
          createdBy: rootUser._id
        };
        
        try {
          const product = await Product.create(productData);
          createdProducts.push(product);
          companySuccess++;
          totalSuccess++;
          
          console.log(`   ✅ [${i + 1}/${companyProducts.length}] ${product.name}`);
          console.log(`      Code: ${product.productCode} | SKU: ${product.sku}`);
          
        } catch (error) {
          companyFail++;
          totalFail++;
          console.log(`   ❌ [${i + 1}/${companyProducts.length}] ${productData.name}`);
          console.log(`      Error: ${error.message}`);
        }
      }
      
      console.log(`\n   📊 ${company.code} Summary: ${companySuccess} success, ${companyFail} failed\n`);
    }
    
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    console.log('📊 OVERALL SEEDING SUMMARY:\n');
    console.log(`   ✅ Successfully created: ${totalSuccess} products`);
    console.log(`   ❌ Failed: ${totalFail} products`);
    console.log(`   🏢 Companies: ${companies.length}\n`);
    
    if (createdProducts.length > 0) {
      console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
      console.log('📦 PRODUCTS BY COMPANY:\n');
      
      for (const company of companies) {
        const companyProds = createdProducts.filter(
          p => p.companyId.toString() === company._id.toString()
        );
        
        if (companyProds.length === 0) continue;
        
        console.log(`\n🏢 ${company.name} (${company.code}) - ${companyProds.length} products:`);
        console.log('   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
        
        companyProds.forEach((product, idx) => {
          console.log(`   ${idx + 1}. ${product.name}`);
          console.log(`      🆔 ID: ${product._id}`);
          console.log(`      📝 Code: ${product.productCode}`);
          console.log(`      🏷️  SKU: ${product.sku}`);
          console.log(`      📂 Category: ${product.category} > ${product.subCategory || 'N/A'}`);
          console.log(`      💰 Price: ₹${product.pricing.price.toLocaleString('en-IN')}`);
          console.log(`      📦 Stock: ${product.inventory.quantity} ${product.inventory.unit}s`);
          console.log(`      ⭐ Rating: ${product.metadata.rating}/5 (${product.metadata.reviews} reviews)`);
          console.log(`      ✓ Status: ${product.status} | Featured: ${product.isFeatured ? 'Yes' : 'No'}\n`);
        });
      }
      
      console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
      console.log('📈 CATEGORY BREAKDOWN:\n');
      
      const categoryCount = {};
      createdProducts.forEach(p => {
        categoryCount[p.category] = (categoryCount[p.category] || 0) + 1;
      });
      
      Object.entries(categoryCount).forEach(([category, count]) => {
        console.log(`   ${category}: ${count} products`);
      });
      console.log('');
      
      console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
      console.log('💰 PRICING SUMMARY:\n');
      
      const totalInventoryValue = createdProducts.reduce(
        (sum, p) => sum + (p.pricing.price * p.inventory.quantity), 0
      );
      const avgPrice = createdProducts.reduce((sum, p) => sum + p.pricing.price, 0) / createdProducts.length;
      
      console.log(`   Total Inventory Value: ₹${totalInventoryValue.toLocaleString('en-IN')}`);
      console.log(`   Average Product Price: ₹${Math.round(avgPrice).toLocaleString('en-IN')}`);
      console.log(`   Total Products in Stock: ${createdProducts.reduce((sum, p) => sum + p.inventory.quantity, 0)}\n`);
    }
    
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    console.log('🎉 Product seeding completed successfully!\n');
    console.log('💡 NEXT STEPS:\n');
    console.log('   1. Products are now available in the system');
    console.log('   2. You can view products by company');
    console.log('   3. Update inventory and pricing as needed');
    console.log('   4. Add product images and additional details\n');
    
    console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
    console.log('📚 USEFUL API ENDPOINTS:\n');
    console.log('   • View all products:');
    console.log('     GET /api/v1/products\n');
    console.log('   • View products by company:');
    console.log('     GET /api/v1/products?companyId={companyId}\n');
    console.log('   • View product details:');
    console.log('     GET /api/v1/products/:productId\n');
    console.log('   • Search products:');
    console.log('     GET /api/v1/products/search?q={query}\n');
    
    process.exit(0);
    
  } catch (error) {
    console.error('\n❌ Error creating products:', error);
    console.error('\nError details:', error.message);
    
    if (error.code === 11000) {
      console.error('\n💡 Duplicate key error');
      const field = Object.keys(error.keyPattern || {})[0];
      console.error(`   Duplicate ${field} found`);
    }
    
    if (error.name === 'ValidationError') {
      console.error('\n💡 Validation errors:');
      Object.keys(error.errors).forEach(key => {
        console.error(`   - ${key}: ${error.errors[key].message}`);
      });
    }
    
    console.error('\n📋 Stack trace:');
    console.error(error.stack);
    console.error('');
    
    process.exit(1);
  }
};

seedProducts();