/**
 * Seed Data Main Script
 * Runs all seeders to populate database with initial data
 */

// Load environment variables
require('dotenv').config();

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

/**
 * Main seeder function
 * Runs all seed scripts in order
 */
const runSeeders = async () => {
  try {
    // Connect to database
    await db.sequelize.authenticate();
    logger.info('Database connection established for seeding.');
    
    // Sync database (create tables if they don't exist)
    await db.sequelize.sync({ alter: false }); // Don't alter, just create if needed
    logger.info('Database tables synced.');
    
    // Run seeders in order (respecting dependencies)
    logger.info('Starting database seeding...');
    
    // Seed Users first (no dependencies)
    await require('./seedUsers')(db);
    
    // Tax seeding removed - tax functionality removed from system
    
    // Seed Categories (self-referential, but can seed root categories first)
    await require('./seedCategories')(db);
    
    // Seed Price Lists (no dependencies)
    await require('./seedPriceLists')(db);
    
    // Seed Products (depends on categories and taxes)
    await require('./seedProducts')(db);
    
    // Seed Inventory (depends on products)
    await require('./seedInventory')(db);
    
    logger.info('✅ All seeders completed successfully!');
    
    // Close database connection
    await db.sequelize.close();
    logger.info('Database connection closed.');
    
    // Exit process
    process.exit(0);
  } catch (error) {
    // Log error and exit with error code
    logger.error('❌ Seeding failed:', error);
    process.exit(1);
  }
};

// Run seeders if script is executed directly
if (require.main === module) {
  runSeeders();
}

// Export for use in other scripts
module.exports = runSeeders;

