/**
 * Inventory Seeder
 * Seeds sample inventory data for products
 */

// Import logger
const logger = require('../../utils/logger');

/**
 * Seed inventory data
 * Creates inventory records for existing products
 * @param {Object} db - Database models object
 */
const seedInventory = async (db) => {
  // Import Inventory, Product, and ProductVariant models from database
  const { Inventory, Product, ProductVariant } = db;
  try {
    logger.info('Starting inventory seeding...'); // Log start
    
    // Get all products
    const products = await Product.findAll({
      include: [
        {
          model: ProductVariant, // Include variants
          as: 'variants', // Use variants alias
          required: false, // Left join (variants may not exist)
        },
      ],
    });
    
    // Check if products exist
    if (products.length === 0) {
      logger.warn('No products found. Please seed products first.'); // Log warning
      return; // Exit early if no products
    }
    
    let inventoryCount = 0; // Counter for created inventory records
    
    // Loop through products
    for (const product of products) {
      // Check if product tracks inventory
      if (!product.track_inventory) {
        continue; // Skip products that don't track inventory
      }
      
      // Get product variants
      const variants = product.variants || []; // Get variants array
      
      // If product has variants, create inventory for each variant
      if (variants.length > 0) {
        for (const variant of variants) {
          // Check if inventory already exists
          const existingInventory = await Inventory.findOne({
            where: {
              product_id: product.id, // Match product ID
              variant_id: variant.id, // Match variant ID
            },
          });
          
          // Skip if inventory already exists
          if (existingInventory) {
            continue; // Skip existing inventory
          }
          
          // Generate random quantity (10-100)
          const quantity = Math.floor(Math.random() * 91) + 10; // Random quantity between 10 and 100
          // Generate random reorder level (5-20)
          const reorderLevel = Math.floor(Math.random() * 16) + 5; // Random reorder level between 5 and 20
          
          // Create inventory record
          await Inventory.create({
            product_id: product.id, // Set product ID
            variant_id: variant.id, // Set variant ID
            quantity: quantity, // Set quantity
            reorder_level: reorderLevel, // Set reorder level
          });
          
          inventoryCount++; // Increment counter
        }
      } else {
        // If product has no variants, create inventory for product only
        // Check if inventory already exists
        const existingInventory = await Inventory.findOne({
          where: {
            product_id: product.id, // Match product ID
            variant_id: null, // No variant
          },
        });
        
        // Skip if inventory already exists
        if (existingInventory) {
          continue; // Skip existing inventory
        }
        
        // Generate random quantity (10-100)
        const quantity = Math.floor(Math.random() * 91) + 10; // Random quantity between 10 and 100
        // Generate random reorder level (5-20)
        const reorderLevel = Math.floor(Math.random() * 16) + 5; // Random reorder level between 5 and 20
        
        // Create inventory record
        await Inventory.create({
          product_id: product.id, // Set product ID
          variant_id: null, // No variant
          quantity: quantity, // Set quantity
          reorder_level: reorderLevel, // Set reorder level
        });
        
        inventoryCount++; // Increment counter
      }
    }
    
    logger.info(`Inventory seeding completed. Created ${inventoryCount} inventory records.`); // Log completion
    
    // Return success
    return { success: true, count: inventoryCount }; // Return success and count
  } catch (error) {
    logger.error('Error seeding inventory:', error); // Log error
    throw error; // Re-throw error
  }
};

// Run seeder if called directly
if (require.main === module) {
  // Load environment variables
  require('dotenv').config();
  
  // Import database connection
  const db = require('../../models'); // Import models (initializes database connection)
  
  // Authenticate database connection
  db.sequelize.authenticate()
    .then(() => {
      logger.info('Database connection established for seeding.'); // Log connection
      // Run seeder
      return seedInventory(db); // Pass db object to seeder
    })
    .then((result) => {
      logger.info('Seeder completed:', result); // Log success
      // Close database connection
      return db.sequelize.close(); // Close connection
    })
    .then(() => {
      logger.info('Database connection closed.'); // Log closure
      process.exit(0); // Exit successfully
    })
    .catch((error) => {
      logger.error('Seeder failed:', error); // Log error
      process.exit(1); // Exit with error
    });
}

// Export seeder function
module.exports = seedInventory;

