import 'package:flutter/foundation.dart';
import 'package:hive_ce_flutter/hive_flutter.dart';

import 'package:worker/core/database/database_manager.dart';
import 'package:worker/core/database/hive_service.dart';

/// Hive Database Initializer
///
/// Provides a simple API for initializing the Hive database
/// in the main.dart file.
///
/// Example usage:
/// ```dart
/// void main() async {
///   WidgetsFlutterBinding.ensureInitialized();
///
///   // Initialize Hive
///   await HiveInitializer.initialize();
///
///   runApp(const MyApp());
/// }
/// ```
class HiveInitializer {
  /// Initialize Hive database
  ///
  /// This method should be called once during app startup.
  /// It initializes Hive, registers adapters, and opens boxes.
  ///
  /// [enableEncryption] - Enable AES encryption for sensitive boxes
  /// [encryptionKey] - Optional custom encryption key (256-bit)
  /// [verbose] - Enable verbose logging for debugging
  static Future<void> initialize({
    bool enableEncryption = false,
    List<int>? encryptionKey,
    bool verbose = false,
  }) async {
    try {
      if (verbose) {
        debugPrint('HiveInitializer: Starting initialization...');
      }

      // Get HiveService instance
      final hiveService = HiveService();

      // Initialize Hive
      await hiveService.initialize(
        encryptionKey: enableEncryption ? encryptionKey : null,
      );

      // Perform initial maintenance
      if (verbose) {
        debugPrint('HiveInitializer: Performing initial maintenance...');
      }

      final dbManager = DatabaseManager();

      // Migration: Delete old favoriteBox (deprecated, replaced with favoriteProductsBox)
      await _deleteLegacyFavoriteBox(verbose);

      // Clear expired cache on app start
      await dbManager.clearExpiredCache();

      // Print statistics in debug mode
      if (verbose && kDebugMode) {
        dbManager.printStatistics();
      }

      if (verbose) {
        debugPrint('HiveInitializer: Initialization complete');
      }
    } catch (e, stackTrace) {
      debugPrint('HiveInitializer: Initialization failed: $e');
      debugPrint('StackTrace: $stackTrace');
      rethrow;
    }
  }

  /// Close Hive database
  ///
  /// Should be called when app is terminating.
  /// Usually not needed for normal app lifecycle.
  static Future<void> close() async {
    final hiveService = HiveService();
    await hiveService.close();
  }

  /// Reset database (clear all data)
  ///
  /// WARNING: This will delete all local data!
  /// Use only for logout or app reset functionality.
  static Future<void> reset() async {
    final hiveService = HiveService();
    await hiveService.clearAllData();
  }

  /// Clear user data (logout)
  ///
  /// Clears user-specific data while preserving app settings and cache.
  static Future<void> logout() async {
    final hiveService = HiveService();
    await hiveService.clearUserData();
  }

  /// Delete legacy favoriteBox (migration helper)
  ///
  /// The old favoriteBox stored FavoriteModel which has been removed.
  /// This method deletes the old box to prevent typeId errors.
  static Future<void> _deleteLegacyFavoriteBox(bool verbose) async {
    try {
      const legacyBoxName = 'favorite_box';

      // Check if the old box exists
      if (await Hive.boxExists(legacyBoxName)) {
        if (verbose) {
          debugPrint('HiveInitializer: Deleting legacy favoriteBox...');
        }

        // Delete the box from disk
        await Hive.deleteBoxFromDisk(legacyBoxName);

        if (verbose) {
          debugPrint('HiveInitializer: Legacy favoriteBox deleted successfully');
        }
      }
    } catch (e) {
      debugPrint('HiveInitializer: Error deleting legacy favoriteBox: $e');
      // Don't rethrow - this is just a cleanup operation
    }
  }

  /// Get database statistics
  ///
  /// Returns statistics about all Hive boxes.
  static Map<String, dynamic> getStatistics() {
    final dbManager = DatabaseManager();
    return dbManager.getStatistics();
  }

  /// Print database statistics (debug only)
  static void printStatistics() {
    if (kDebugMode) {
      final dbManager = DatabaseManager();
      dbManager.printStatistics();
    }
  }
}
