const bcrypt = require('bcryptjs');
require('dotenv').config();
const { getCollections, getNextSequence } = require('./db');

async function ensureSeed() {
  const { users, products, customers } = await getCollections();

  const existingUsers = await users.countDocuments({ email: 'admin@smartshop.com' });
  if (existingUsers === 0) {
    const hashed = await bcrypt.hash('admin123', 10);
    const adminId = await getNextSequence('users');
    await users.insertOne({
      id: adminId,
      full_name: 'Admin User',
      email: 'admin@smartshop.com',
      password: hashed,
      role: 'admin',
      created_at: new Date()
    });
  }

  const productCount = await products.countDocuments({});
  if (productCount === 0) {
    const sampleProducts = [
      ['Samsung Galaxy S24', 'Phones', 850000, 25],
      ['iPhone 15 Pro', 'Phones', 1200000, 15],
      ['Dell Inspiron 15', 'Laptops', 950000, 10],
      ['HP Pavilion x360', 'Laptops', 1100000, 8],
      ['Samsung 55" Smart TV', 'Televisions', 750000, 12],
      ['LG 43" 4K TV', 'Televisions', 550000, 20],
      ['USB-C Hub 7-in-1', 'Accessories', 35000, 50],
      ['Wireless Earbuds Pro', 'Accessories', 85000, 40],
      ['Laptop Bag Premium', 'Accessories', 45000, 30],
      ['Screen Protector Pack', 'Accessories', 12000, 100]
    ];

    for (const [product_name, category, price, stock] of sampleProducts) {
      const product_id = await getNextSequence('products');
      await products.insertOne({
        product_id,
        product_name,
        category,
        price,
        stock: stock || 0,
        created_date: new Date()
      });
    }
  }

  const customerCount = await customers.countDocuments({});
  if (customerCount === 0) {
    const sampleCustomers = [
      ['Jean Baptiste Nkurunziza', '0788123456', 'jean@email.com', 'Kigali, Gasabo'],
      ['Marie Claire Uwimana', '0722987654', 'marie@email.com', 'Kigali, Kicukiro'],
      ['Patrick Habimana', '0733456789', 'patrick@email.com', 'Kigali, Nyarugenge']
    ];

    for (const [full_name, phone_number, email, address] of sampleCustomers) {
      const customer_id = await getNextSequence('customers');
      await customers.insertOne({
        customer_id,
        full_name,
        phone_number,
        email: email || null,
        address: address || null,
        registration_date: new Date()
      });
    }
  }
}

module.exports = { ensureSeed };

