require('dotenv').config();
const bcrypt = require('bcryptjs');
const sequelize = require('../config/database');
const models = require('../models/associations');
const { User, Category, Product, ProductImage, Banner, Page, Setting, Coupon } = models;

async function runSeeders() {
  try {
    await sequelize.sync({ force: true });
    console.log('Database reset and synced.');

    // Admin user
    const adminPassword = await bcrypt.hash('admin123', 10);
    await User.create({
      name: 'Admin',
      email: 'admin@shopnow.com',
      password: adminPassword,
      phone: '9876543210',
      isAdmin: true,
      isActive: true,
      address: '123 Admin Street',
      city: 'Mumbai',
      state: 'Maharashtra',
      pincode: '400001',
    });
    console.log('Admin created: admin@shopnow.com / admin123');

    // Customer
    const userPassword = await bcrypt.hash('user123', 10);
    await User.create({
      name: 'Rahul Sharma',
      email: 'rahul@example.com',
      password: userPassword,
      phone: '9876543211',
      isAdmin: false,
      isActive: true,
      address: '456 Customer Lane',
      city: 'Delhi',
      state: 'Delhi',
      pincode: '110001',
    });
    console.log('Customer created: rahul@example.com / user123');

    // Categories
    const catData = [
      { name: 'Electronics', slug: 'electronics', description: 'Gadgets, devices & accessories', sortOrder: 1 },
      { name: 'Clothing', slug: 'clothing', description: 'Fashion for men, women & kids', sortOrder: 2 },
      { name: 'Home & Kitchen', slug: 'home-kitchen', description: 'Furniture, decor & kitchen appliances', sortOrder: 3 },
      { name: 'Books', slug: 'books', description: 'Books, ebooks & magazines', sortOrder: 4 },
      { name: 'Sports & Fitness', slug: 'sports-fitness', description: 'Sports equipment, gym gear & activewear', sortOrder: 5 },
      { name: 'Beauty & Personal Care', slug: 'beauty-care', description: 'Skincare, makeup & grooming', sortOrder: 6 },
    ];
    const categories = await Category.bulkCreate(catData);
    console.log('Categories created:', categories.length);

    // Subcategories
    await Category.bulkCreate([
      { name: 'Mobile Phones', slug: 'mobile-phones', description: 'Smartphones & accessories', parentId: categories[0].id, sortOrder: 1 },
      { name: 'Laptops', slug: 'laptops', description: 'Laptops & computers', parentId: categories[0].id, sortOrder: 2 },
      { name: 'Men', slug: 'men-clothing', description: "Men's clothing", parentId: categories[1].id, sortOrder: 1 },
      { name: 'Women', slug: 'women-clothing', description: "Women's clothing", parentId: categories[1].id, sortOrder: 2 },
    ]);

    // Products
    const productsData = [
      { name: 'Wireless Bluetooth Headphones', slug: 'wireless-bluetooth-headphones', description: 'Premium wireless headphones with noise cancellation. 30-hour battery life, comfortable over-ear design, crystal clear audio.', shortDescription: 'Premium wireless headphones with ANC', price: 2499, comparePrice: 3999, stockQuantity: 50, sku: 'ELEC-HP-001', categoryId: categories[0].id, isFeatured: true },
      { name: 'Smart Watch Pro', slug: 'smart-watch-pro', description: 'Advanced smartwatch with health tracking, GPS, heart rate monitor, sleep tracking, and 7-day battery life.', shortDescription: 'Advanced health tracking smartwatch', price: 3999, comparePrice: 5999, stockQuantity: 35, sku: 'ELEC-SW-001', categoryId: categories[0].id, isFeatured: true },
      { name: 'Cotton Casual Shirt', slug: 'cotton-casual-shirt', description: 'Premium cotton casual shirt. Breathable fabric, perfect for daily wear. Available in multiple colors.', shortDescription: 'Premium cotton shirt for daily wear', price: 899, comparePrice: 1499, stockQuantity: 100, sku: 'CLOTH-SH-001', categoryId: categories[1].id, isFeatured: true },
      { name: 'Stainless Steel Water Bottle', slug: 'stainless-steel-bottle', description: 'Double-wall insulated water bottle. Keeps drinks cold for 24hrs or hot for 12hrs. 750ml capacity.', shortDescription: 'Insulated bottle, 750ml', price: 599, comparePrice: 999, stockQuantity: 80, sku: 'HOME-BT-001', categoryId: categories[2].id, isFeatured: true },
      { name: 'Yoga Mat Premium', slug: 'yoga-mat-premium', description: 'Extra thick, non-slip yoga mat. Perfect for yoga, pilates, and floor exercises. Includes carrying strap.', shortDescription: 'Extra thick non-slip yoga mat', price: 1299, comparePrice: 1999, stockQuantity: 60, sku: 'SPRT-YM-001', categoryId: categories[4].id, isFeatured: true },
      { name: 'Organic Face Serum', slug: 'organic-face-serum', description: 'Vitamin C face serum with hyaluronic acid. Natural ingredients, suitable for all skin types.', shortDescription: 'Vitamin C serum for glowing skin', price: 449, comparePrice: 699, stockQuantity: 90, sku: 'BEAU-SR-001', categoryId: categories[5].id, isFeatured: false },
      { name: 'USB-C Fast Charger', slug: 'usb-c-fast-charger', description: '65W GaN fast charger. Compatible with laptops, phones, and tablets. Compact design with foldable pins.', shortDescription: '65W GaN fast charger', price: 1499, comparePrice: 2499, stockQuantity: 45, sku: 'ELEC-CH-001', categoryId: categories[0].id, isFeatured: false },
      { name: 'Leather Wallet', slug: 'leather-wallet', description: 'Genuine leather wallet with RFID blocking. Multiple card slots, coin pocket, and note compartment.', shortDescription: 'Genuine leather RFID wallet', price: 699, comparePrice: 1299, stockQuantity: 70, sku: 'CLOTH-WL-001', categoryId: categories[1].id, isFeatured: false },
      { name: 'Non-Stick Cookware Set', slug: 'non-stick-cookware-set', description: '5-piece non-stick cookware set. Includes frying pan, sauce pan, and cooking utensils. Dishwasher safe.', shortDescription: '5-piece non-stick cookware set', price: 2499, comparePrice: 3999, stockQuantity: 25, sku: 'HOME-CK-001', categoryId: categories[2].id, isFeatured: false },
      { name: 'Running Shoes Ultra', slug: 'running-shoes-ultra', description: 'Lightweight running shoes with responsive cushioning. Breathable mesh upper, durable rubber outsole.', shortDescription: 'Lightweight running shoes', price: 2999, comparePrice: 4999, stockQuantity: 40, sku: 'SPRT-SH-001', categoryId: categories[4].id, isFeatured: false },
    ];
    const products = await Product.bulkCreate(productsData);
    console.log('Products created:', products.length);

    // Product Images (placeholder)
    for (const product of products) {
      await ProductImage.create({
        productId: product.id,
        imagePath: '/uploads/products/placeholder.svg',
        isPrimary: true,
        sortOrder: 0,
      });
    }

    // Banners
    await Banner.bulkCreate([
      { title: 'Summer Sale', subtitle: 'Up to 50% off on trending items', image: '/uploads/banners/placeholder.svg', link: '/products', btnText: 'Shop Now', sortOrder: 1, isActive: true },
      { title: 'New Arrivals', subtitle: 'Check out our latest collection', image: '/uploads/banners/placeholder.svg', link: '/products?sort=newest', btnText: 'Explore', sortOrder: 2, isActive: true },
    ]);
    console.log('Banners created');

    // Pages
    await Page.bulkCreate([
      { title: 'About Us', slug: 'about', content: 'Welcome to ShopNow!\n\nWe are your one-stop destination for quality products at the best prices. Founded in 2024, we have been serving thousands of happy customers across India.\n\nOur mission is to provide a seamless shopping experience with the widest selection of products, fastest delivery, and the best customer service.\n\nThank you for choosing us!', isPublished: true, sortOrder: 1 },
      { title: 'Contact Us', slug: 'contact', content: 'Get in touch with us:\n\n📍 Address: 123 Main Street, Mumbai, Maharashtra - 400001\n📞 Phone: +91 9876543210\n📧 Email: support@shopnow.com\n\nBusiness Hours:\nMonday - Saturday: 9:00 AM - 8:00 PM\nSunday: 10:00 AM - 6:00 PM', isPublished: true, sortOrder: 2 },
      { title: 'Shipping Policy', slug: 'shipping', content: 'Shipping Policy\n\nWe offer free shipping on orders above ₹500. For orders below ₹500, a flat shipping fee of ₹50 applies.\n\nOrders are processed within 24 hours and delivered within 3-7 business days across India.\n\nCash on Delivery and prepaid payment options are available.', isPublished: true, sortOrder: 3 },
      { title: 'Returns Policy', slug: 'returns', content: 'Returns Policy\n\nWe offer a 7-day easy return policy. If you are not satisfied with your purchase, you can return it within 7 days of delivery.\n\nItems must be unused and in their original packaging. Return shipping is free for defective items.\n\nRefunds are processed within 5-7 business days after we receive the returned item.', isPublished: true, sortOrder: 4 },
    ]);
    console.log('Pages created');

    // Coupons
    await Coupon.bulkCreate([
      { code: 'WELCOME10', type: 'percentage', value: 10, minOrderAmount: 500, maxDiscountAmount: 200, maxUses: 100, isActive: true, description: '10% off for new customers (max ₹200 off)' },
      { code: 'SAVE500', type: 'fixed', value: 500, minOrderAmount: 2500, maxUses: 50, isActive: true, description: '₹500 off on orders above ₹2500' },
      { code: 'FREESHIP', type: 'fixed', value: 50, minOrderAmount: 0, maxUses: 200, isActive: true, description: 'Free shipping (₹50 off)' },
    ]);
    console.log('Coupons created');

    // Settings
    await Setting.bulkCreate([
      { key: 'store_name', value: 'ShopNow', type: 'text', group: 'general', label: 'Store Name' },
      { key: 'store_email', value: 'support@shopnow.com', type: 'email', group: 'general', label: 'Store Email' },
      { key: 'store_phone', value: '+91 9876543210', type: 'text', group: 'general', label: 'Store Phone' },
      { key: 'store_address', value: '123 Main Street, Mumbai, Maharashtra - 400001', type: 'textarea', group: 'general', label: 'Store Address' },
      { key: 'currency', value: 'INR', type: 'select', group: 'general', label: 'Currency' },
      { key: 'tax_rate', value: '18', type: 'number', group: 'shipping', label: 'Tax Rate (%)' },
      { key: 'shipping_flat_rate', value: '50', type: 'number', group: 'shipping', label: 'Flat Shipping Rate' },
      { key: 'shipping_free_min_amount', value: '500', type: 'number', group: 'shipping', label: 'Free Shipping Min Amount' },
    ]);
    console.log('Settings created');

    // Placeholder SVG
    const fs = require('fs');
    const path = require('path');
    const placeholderSvg = `<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400" viewBox="0 0 400 400"><rect width="400" height="400" fill="#f3f4f6"/><text x="200" y="200" text-anchor="middle" fill="#9ca3af" font-size="40" font-family="Arial" dy=".3em">No Image</text></svg>`;
    ['products', 'banners', 'categories'].forEach(dir => {
      const filePath = path.join(__dirname, '..', 'public', 'uploads', dir, 'placeholder.svg');
      fs.writeFileSync(filePath, placeholderSvg);
    });
    console.log('Placeholder images created');

    console.log('\n=============================');
    console.log('  Seeding Complete!');
    console.log('=============================');
    console.log('  Admin: admin@shopnow.com / admin123');
    console.log('  User:  rahul@example.com / user123');
    console.log('  Products: ' + products.length);
    console.log('  Categories: ' + categories.length);
    console.log('=============================');

    process.exit(0);
  } catch (error) {
    console.error('Seeding error:', error);
    process.exit(1);
  }
}

runSeeders();
