import 'package:dio/dio.dart';
import 'package:be_happy/presentation/viewmodel/splash_bloc.dart';
import 'package:be_happy/presentation/event/spalsh_event.dart';

import '../../di/service_locator.dart';

class AuthInterceptor extends Interceptor {

  AuthInterceptor();

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    final String path = err.requestOptions.path;

    if (err.response?.statusCode == 401) {
      if (!path.contains('/auth/client/refresh') && !path.contains('/auth/client/login')) {
        print('Interceptor: 401 на обычном запросе. Пытаемся обновить токен...');
        getIt<SplashBloc>().add(AuthCheckRequested());
      } else {
        print('Interceptor: 401 на запросе авторизации. Пробрасываем ошибку дальше.');
      }
    }

    return super.onError(err, handler);
  }
}