import 'package:flutter_riverpod/flutter_riverpod.dart';

import 'api_exception.dart';
import '../../features/auth/data/auth_providers.dart';

/// Executes [call] and automatically logs out the user if the server
/// returns 401 Unauthorized. Re-throws the exception so the calling
/// widget/provider can still display an error if needed.
Future<T> guardedApiCall<T>(Ref ref, Future<T> Function() call) async {
  try {
    return await call();
  } on ApiException catch (e) {
    if (e.type == ApiErrorType.unauthorized) {
      await ref.read(authStateProvider.notifier).logout();
    }
    rethrow;
  }
}
