// Package imports:
import 'package:dio/dio.dart';
import 'package:dio_smart_retry/dio_smart_retry.dart';
import 'package:remever/common/functions.dart';
import 'package:talker_dio_logger/talker_dio_logger_interceptor.dart';
import 'package:talker_dio_logger/talker_dio_logger_settings.dart';

// Project imports:
import '../../components/env.dart';

///
/// Обработчик на события для авторизации
///
InterceptorsWrapper get _auth {
  return InterceptorsWrapper(
    onRequest: (
      RequestOptions options,
      RequestInterceptorHandler handler,
    ) async {
      // try {
      //   String? token = await authSecStorage.read(key: StorageKeys.authToken);

      //   if (token != null) {
      //     options.headers['Authorization'] = 'Bearer $token';
      //   }
      // } catch (e) {
      //   getIt<LogService>().log(
      //     entity: LogEntity.error(message: 'Error to load access token $e'),
      //   );
      // }

      return handler.next(options);
    },
  );
}

InterceptorsWrapper get _error {
  return InterceptorsWrapper(
    onError: (DioException error, ErrorInterceptorHandler handler) async {
      final int? statusCode = error.response?.statusCode;

      if (statusCode == 401) {
        // String? token = await getIt<AuthService>().refresh();
      }

      handler.next(error);
    },
  );
}

///
/// API клиент для работы с бекендом
///
Dio get apiClient {
  final Dio client = Dio(
    BaseOptions(
      baseUrl: Env.get.url.toString(),
      contentType: 'application/json',
    ),
  );

  client.interceptors
    ..add(_auth)
    ..add(_error)
    ..add(
      TalkerDioLogger(
        talker: talker,
        settings: const TalkerDioLoggerSettings(printRequestHeaders: true),
      ),
    )
    ..add(
      RetryInterceptor(
        dio: client,
        logPrint: print,
        retries: 1,
        retryDelays: <Duration>[const Duration(seconds: 1)],
      ),
    );

  return client;
}
