import { NextResponse } from "next/server";
import { getCollection } from "@/lib/mongodb";

// Generate 1000+ dummy products
function generateDummyProducts(count: number = 1200) {
  const categories = [
    "Laptops", "Desktops", "Gaming Accessories", "Monitors", "Storage", 
    "Graphics Cards", "Computer Accessories", "Audio", "Keyboards", "Mice",
    "Headsets", "Webcams", "USB Hubs", "Hard Drives", "SSDs", "RAM",
    "Motherboards", "Processors", "Cooling", "Power Supplies", "Cases",
    "Networking", "Printers", "Scanners", "Tablets", "Smartphones"
  ];

  const brands = [
    "ASUS", "HP", "Dell", "Lenovo", "Acer", "MSI", "Samsung", "LG",
    "Logitech", "Corsair", "SteelSeries", "Razer", "HyperX", "NVIDIA",
    "AMD", "Intel", "Western Digital", "Seagate", "Kingston", "Crucial",
    "Gigabyte", "ASRock", "EVGA", "Cooler Master", "Thermaltake", "Anker"
  ];

  const suppliers = [
    "ASUS Distribution", "HP Official", "Dell Direct", "Lenovo Store",
    "Samsung Official", "Logitech Official", "Corsair Distribution",
    "NVIDIA Partner", "Western Digital Official", "Anker Official"
  ];

  const racks = ["A-101", "A-102", "B-201", "B-202", "C-301", "C-302", "D-401", "D-402", "E-501", "E-502"];

  const products: any[] = [];
  const baseProducts = [
    { name: "Gaming Laptop", basePrice: 1200, baseCost: 900, category: "Laptops" },
    { name: "Business Laptop", basePrice: 800, baseCost: 600, category: "Laptops" },
    { name: "Ultrabook", basePrice: 1000, baseCost: 750, category: "Laptops" },
    { name: "Gaming Desktop", basePrice: 1500, baseCost: 1100, category: "Desktops" },
    { name: "Workstation", basePrice: 2000, baseCost: 1500, category: "Desktops" },
    { name: "Gaming Mouse", basePrice: 80, baseCost: 45, category: "Gaming Accessories" },
    { name: "Mechanical Keyboard", basePrice: 150, baseCost: 90, category: "Gaming Accessories" },
    { name: "Gaming Headset", basePrice: 120, baseCost: 70, category: "Audio" },
    { name: "4K Monitor", basePrice: 400, baseCost: 280, category: "Monitors" },
    { name: "Gaming Monitor", basePrice: 350, baseCost: 250, category: "Monitors" },
    { name: "SSD 1TB", basePrice: 100, baseCost: 65, category: "Storage" },
    { name: "SSD 2TB", basePrice: 180, baseCost: 120, category: "Storage" },
    { name: "HDD 2TB", basePrice: 60, baseCost: 40, category: "Storage" },
    { name: "HDD 4TB", basePrice: 90, baseCost: 60, category: "Storage" },
    { name: "Graphics Card RTX 4070", basePrice: 600, baseCost: 450, category: "Graphics Cards" },
    { name: "Graphics Card RTX 4080", basePrice: 1200, baseCost: 950, category: "Graphics Cards" },
    { name: "Graphics Card RTX 4090", basePrice: 1600, baseCost: 1300, category: "Graphics Cards" },
    { name: "Webcam HD", basePrice: 50, baseCost: 30, category: "Computer Accessories" },
    { name: "Webcam 4K", basePrice: 150, baseCost: 90, category: "Computer Accessories" },
    { name: "USB Hub", basePrice: 30, baseCost: 18, category: "Computer Accessories" },
    { name: "USB-C Hub", basePrice: 45, baseCost: 25, category: "Computer Accessories" },
    { name: "RAM 16GB", basePrice: 80, baseCost: 55, category: "RAM" },
    { name: "RAM 32GB", basePrice: 150, baseCost: 100, category: "RAM" },
    { name: "Motherboard", basePrice: 200, baseCost: 140, category: "Motherboards" },
    { name: "Processor", basePrice: 300, baseCost: 220, category: "Processors" },
    { name: "CPU Cooler", basePrice: 60, baseCost: 40, category: "Cooling" },
    { name: "Power Supply 750W", basePrice: 100, baseCost: 65, category: "Power Supplies" },
    { name: "PC Case", basePrice: 80, baseCost: 50, category: "Cases" },
    { name: "WiFi Router", basePrice: 120, baseCost: 75, category: "Networking" },
    { name: "Network Switch", basePrice: 50, baseCost: 30, category: "Networking" },
  ];

  for (let i = 0; i < count; i++) {
    const baseProduct = baseProducts[i % baseProducts.length];
    const brand = brands[i % brands.length];
    const category = categories[i % categories.length];
    const supplier = suppliers[i % suppliers.length];
    const rack = racks[i % racks.length];
    
    // Add variation to prices
    const priceVariation = (Math.random() * 0.3 - 0.15); // ±15%
    const price = Math.round((baseProduct.basePrice * (1 + priceVariation)) * 100) / 100;
    const cost = Math.round((baseProduct.baseCost * (1 + priceVariation)) * 100) / 100;
    const newCost = Math.round((cost * 0.95) * 100) / 100;
    
    const productNumber = String(i + 1).padStart(4, '0');
    const sku = `PROD-${brand.substring(0, 4).toUpperCase()}-${productNumber}`;
    const itn = `${brand.substring(0, 3)}-${productNumber}`;
    
    const product = {
      title: `${brand} ${baseProduct.name} ${i > 0 ? `- Model ${productNumber}` : ''}`,
      sku: sku,
      itc1: category.substring(0, 8).toUpperCase(),
      itn: itn,
      bcode1: `BC${productNumber}${i}`,
      shortDescription: `High-quality ${baseProduct.name.toLowerCase()} from ${brand}. Perfect for your computing needs.`,
      description: `Premium ${baseProduct.name.toLowerCase()} manufactured by ${brand}. Features top-quality components and reliable performance.`,
      fullDescription: `The ${brand} ${baseProduct.name} is a high-performance product designed for modern computing needs. It features advanced technology and reliable construction, making it perfect for both professional and personal use. This product offers excellent value and performance.`,
      productDetails: JSON.stringify({
        brand: brand,
        model: `Model ${productNumber}`,
        category: category,
        warranty: "1-2 Years",
        weight: `${(Math.random() * 5 + 0.5).toFixed(2)}kg`,
        dimensions: `${(Math.random() * 30 + 10).toFixed(0)} x ${(Math.random() * 20 + 5).toFixed(0)} x ${(Math.random() * 10 + 2).toFixed(0)} cm`,
      }),
      price: price,
      cost: cost,
      newCost: newCost,
      lastSell: price,
      qty: Math.floor(Math.random() * 50) + 5,
      stock: Math.floor(Math.random() * 50) + 5,
      scat: category,
      cat: category,
      itc: "Electronics",
      category: category,
      supplier: supplier,
      mfg: brand,
      vat: 15,
      unit: "PCS",
      rack: rack,
      images: [
        `https://picsum.photos/800/600?random=${i}`,
        `https://picsum.photos/800/600?random=${i + 1000}`,
      ],
      photoUrl: `https://picsum.photos/800/600?random=${i}`,
      active: true,
      featured: i < 50, // First 50 products are featured
      createdAt: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toISOString(),
      updatedAt: new Date().toISOString(),
    };
    
    products.push(product);
  }
  
  return products;
}

export async function POST(request: Request) {
  try {
    const url = new URL(request.url);
    const count = parseInt(url.searchParams.get("count") || "1200", 10);
    
    const ecommersCollection = await getCollection<any>("ecommers");
    
    // Generate products
    const products = generateDummyProducts(count);
    
    // Insert products in batches of 100 to avoid memory issues
    const batchSize = 100;
    let insertedCount = 0;
    const errors: string[] = [];
    
    for (let i = 0; i < products.length; i += batchSize) {
      const batch = products.slice(i, i + batchSize);
      try {
        const result = await ecommersCollection.insertMany(batch, { ordered: false });
        insertedCount += result.insertedCount;
      } catch (error: any) {
        // Some products might already exist, continue with others
        if (error.code === 11000) {
          // Duplicate key error - skip these
          errors.push(`Batch ${Math.floor(i / batchSize) + 1}: Some products already exist`);
        } else {
          errors.push(`Batch ${Math.floor(i / batchSize) + 1}: ${error.message}`);
        }
      }
    }
    
    return NextResponse.json({
      success: true,
      message: `Successfully added ${insertedCount} products`,
      insertedCount: insertedCount,
      requested: count,
      errors: errors.length > 0 ? errors : undefined,
    });
  } catch (error) {
    console.error("Error seeding products:", error);
    return NextResponse.json(
      {
        error: "Failed to seed products",
        details: error instanceof Error ? error.message : "Unknown error",
      },
      { status: 500 }
    );
  }
}
