import '../../core.dart';

class ApiHandler {
  static bool _isRefreshing = false;
  static bool _isRedirecting = false;
  static CancelToken globalCancelToken = CancelToken();

  static Future<void> reset() async {
    _isRefreshing = false;
    _isRedirecting = false;
    globalCancelToken = CancelToken();
  }


  static void cancelAllRequests(String reason) {
    if (!globalCancelToken.isCancelled) {
      globalCancelToken.cancel(reason);
    }
    globalCancelToken = CancelToken();
  }

  static bool get isRefreshing => _isRefreshing;
  static set isRefreshing(bool val) => _isRefreshing = val;

  static bool get isRedirecting => _isRedirecting;
  static set isRedirecting(bool val) => _isRedirecting = val;
}

typedef AppAsyncCallback<T> = Future<T> Function();
typedef ErrorCallback = Function(dynamic error, StackTrace? stackTrace);
typedef VoidCallback = void Function();

/// this is global safe call function
/// A utility function to safely cal  l an asynchronous function with error
/// handling and optional loading, success, and error messages.
Future<void> gSafeCall<T>({
  required AppAsyncCallback<T> call,
  Function(T result)? onSuccess,
  ErrorCallback? onError,
  VoidCallback? onComplete,
  bool showLoading = false,
  bool showError = false,
  bool showSuccess = false,
  bool showToast = false,
  bool showSnackBar = false,
  Function()? onShowLoading,
  Function()? onHideLoading,
  Function()? onShowSuccessMessage,
  Function()? onShowErrorMessage,
}) async {
  try {
    if (showLoading) (onShowLoading ?? _defaultShowLoading)();
    final result = await call();
    if (showSuccess) (onShowSuccessMessage ?? _defaultShowSuccessMessage)();
    onSuccess?.call(result);
  } catch (error, stackTrace) {
    if (showError) (onShowErrorMessage ?? _defaultShowErrorMessage)();
    onError?.call(error, stackTrace);
  } finally {
    if (showLoading) (onHideLoading ?? _defaultHideLoading)();
    onComplete?.call();
  }
}


void _defaultShowLoading() {
  // پیاده‌سازی پیش‌فرض
}

void _defaultHideLoading() {
  // پیاده‌سازی پیش‌فرض
}

void _defaultShowSuccessMessage() {
  // پیاده‌سازی پیش‌فرض
}

void _defaultShowErrorMessage() {
  // پیاده‌سازی پیش‌فرض
}

bool isTokenExpiredError(dynamic error) {
  return error is DioException && error.response?.statusCode == 401;
}
