import 'package:retail/core/database/hive_database.dart'; import 'package:retail/core/database/seed_data.dart'; /// Database initialization and seeding utility class DatabaseInitializer { final HiveDatabase _database; DatabaseInitializer(this._database); /// Initialize database and seed with sample data if empty Future initialize({bool seedIfEmpty = true}) async { // Initialize Hive await _database.init(); // Seed data if boxes are empty and seeding is enabled if (seedIfEmpty) { await _seedIfEmpty(); } } /// Seed database with sample data if empty Future _seedIfEmpty() async { final productsBox = _database.productsBox; final categoriesBox = _database.categoriesBox; // Check if database is empty if (productsBox.isEmpty && categoriesBox.isEmpty) { await seedDatabase(forceReseed: false); } } /// Seed database with sample data Future seedDatabase({bool forceReseed = false}) async { final productsBox = _database.productsBox; final categoriesBox = _database.categoriesBox; // Clear existing data if force reseed if (forceReseed) { await productsBox.clear(); await categoriesBox.clear(); } // Only seed if boxes are empty if (productsBox.isEmpty && categoriesBox.isEmpty) { // Generate and save categories final categories = SeedData.generateCategories(); final categoriesMap = { for (var category in categories) category.id: category }; await categoriesBox.putAll(categoriesMap); // Generate and save products final products = SeedData.generateProducts(); final productsMap = { for (var product in products) product.id: product }; await productsBox.putAll(productsMap); // Update category product counts await _updateCategoryProductCounts(); } } /// Update product counts for all categories Future _updateCategoryProductCounts() async { final productsBox = _database.productsBox; final categoriesBox = _database.categoriesBox; // Count products per category final productCounts = {}; for (var product in productsBox.values) { productCounts[product.categoryId] = (productCounts[product.categoryId] ?? 0) + 1; } // Update category product counts for (var category in categoriesBox.values) { final count = productCounts[category.id] ?? 0; if (category.productCount != count) { final updated = category.copyWith(productCount: count); await categoriesBox.put(category.id, updated); } } } /// Reset database (clear all data and reseed) Future resetDatabase() async { await _database.clearAllData(); await seedDatabase(forceReseed: true); } /// Get database statistics Map getDatabaseStats() { return _database.getStatistics(); } /// Compact database (optimize storage) Future compactDatabase() async { await _database.compactAll(); } }