import 'package:flutter_modular/flutter_modular.dart';

/// Base navigation utilities extension for [IModularNavigator].
///
/// Provides helper methods for common navigation patterns that can be used
/// across both Client and Staff applications. These utilities add error handling,
/// logging capabilities, and convenience methods on top of the base Modular
/// navigation API.
///
/// See also:
///  * [ClientNavigator] for Client-specific navigation
///  * [StaffNavigator] for Staff-specific navigation
extension NavigationExtensions on IModularNavigator {
  /// Safely navigates to a route with optional error handling.
  ///
  /// This method wraps [navigate] with error handling to prevent navigation
  /// failures from crashing the app.
  ///
  /// Parameters:
  ///  * [path] - The route path to navigate to
  ///  * [arguments] - Optional arguments to pass to the route
  ///
  /// Returns `true` if navigation was successful, `false` otherwise.
  Future<bool> safeNavigate(
    String path, {
    Object? arguments,
  }) async {
    try {
      navigate(path, arguments: arguments);
      return true;
    } catch (e) {
      // In production, you might want to log this to a monitoring service
      // ignore: avoid_print
      print('Navigation error to $path: $e');
      return false;
    }
  }

  /// Safely pushes a named route with optional error handling.
  ///
  /// This method wraps [pushNamed] with error handling to prevent navigation
  /// failures from crashing the app.
  ///
  /// Parameters:
  ///  * [routeName] - The name of the route to push
  ///  * [arguments] - Optional arguments to pass to the route
  ///
  /// Returns the result from the pushed route, or `null` if navigation failed.
  Future<T?> safePush<T extends Object?>(
    String routeName, {
    Object? arguments,
  }) async {
    try {
      return await pushNamed<T>(routeName, arguments: arguments);
    } catch (e) {
      // In production, you might want to log this to a monitoring service
      // ignore: avoid_print
      print('Push navigation error to $routeName: $e');
      return null;
    }
  }

  /// Pops all routes until reaching the root route.
  ///
  /// This is useful for resetting the navigation stack, such as after logout
  /// or when returning to the main entry point of the app.
  void popToRoot() {
    navigate('/');
  }

  /// Pops the current route if possible.
  ///
  /// Returns `true` if a route was popped, `false` if already at root.
  bool popSafe() {
    if (canPop()) {
      pop();
      return true;
    }
    return false;
  }
}
