const bcrypt = require('bcryptjs');
const mysql = require('mysql2/promise');
require('dotenv').config();

async function seed() {
  const connection = await mysql.createConnection({
    host: process.env.DB_HOST || 'localhost',
    user: process.env.DB_USER || 'root',
    password: process.env.DB_PASSWORD || '',
    database: process.env.DB_NAME || 'smartshop_db',
  });

  try {
    const hashedPassword = await bcrypt.hash('admin123', 10);
    await connection.query(
      'INSERT IGNORE INTO users (username, password) VALUES (?, ?)',
      ['admin', hashedPassword]
    );
    console.log('Default admin user created (username: admin, password: admin123)');

    const [products] = await connection.query('SELECT COUNT(*) AS count FROM products');
    if (products[0].count === 0) {
      await connection.query(`
        INSERT INTO products (product_name, category, quantity, price) VALUES
        ('iPhone 15 Pro', 'Phones', 25, 999.99),
        ('Samsung Galaxy S24', 'Phones', 30, 899.99),
        ('MacBook Pro 14"', 'Laptops', 15, 1999.99),
        ('Dell XPS 15', 'Laptops', 20, 1499.99),
        ('Sony Bravia 55"', 'Televisions', 10, 799.99),
        ('LG OLED 65"', 'Televisions', 8, 1299.99),
        ('AirPods Pro', 'Accessories', 50, 249.99),
        ('USB-C Hub', 'Accessories', 100, 49.99)
      `);
      console.log('Sample products inserted.');
    }

    const [customers] = await connection.query('SELECT COUNT(*) AS count FROM customers');
    if (customers[0].count === 0) {
      await connection.query(`
        INSERT INTO customers (fullname, phone_number, email, address) VALUES
        ('John Smith', '+1234567890', 'john@email.com', '123 Main St, New York'),
        ('Jane Doe', '+0987654321', 'jane@email.com', '456 Oak Ave, Los Angeles'),
        ('Mike Johnson', '+1122334455', 'mike@email.com', '789 Pine Rd, Chicago')
      `);
      console.log('Sample customers inserted.');
    }

    console.log('Seed completed successfully.');
  } catch (error) {
    console.error('Seed error:', error);
  } finally {
    await connection.end();
  }
}

seed();
